package at.spengergasse.service;

import at.spengergasse.domain.Order;
import at.spengergasse.domain.OrderException;
import at.spengergasse.repository.OrderRepository;
import com.github.javafaker.Faker;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class OrderService {
    private final OrderRepository orderRepositroy;

    public OrderService(OrderRepository orderRepository) {
        this.orderRepositroy = orderRepository;

        if (orderRepositroy.count() == 0)
            fillTestdata(30);
    }

    public void fillTestdata(int amount) {
        Faker faker;
        Order order;
        LocalDate orderDate;
        String    pizza;
        String    size;
        Integer   quantity;
        Double    price;
        Boolean   garlic;
        String[] PIZZAS = {"Margherita", "Salami", "Tonno", "Hawaii", "Funghi", "Diavolo"};
        String[] SIZES = { "Small", "Medium", "Large", "Family" };

        faker = new Faker();

        for (int i=0; i<amount; i++) {
            orderDate = LocalDate.now().minusDays((int) (Math.random() * 365 * 10));
            pizza = PIZZAS[faker.number().numberBetween(0, PIZZAS.length - 1)];
            size = SIZES[faker.number().numberBetween(0, SIZES.length - 1)];
            quantity = faker.number().numberBetween(1, 5);
            price = faker.number().randomDouble(2, 10, 50);
            garlic = faker.bool().bool();
            order = new Order(orderDate, pizza, size, quantity, price, garlic);
            orderRepositroy.save(order);
        }
    }

    public ArrayList<Order> findAll() {
        ArrayList<Order> copy;

        copy = (ArrayList<Order>) orderRepositroy.findAll();
        return copy;
    }

    @Override
    public String toString() {
        return orderRepositroy.findAll().stream()
                .map(o -> o.toString())
                .collect(Collectors.joining("\n")).toString();
    }

    public void removeAllOrders() {
        orderRepositroy.deleteAll();
    }

    public void addOrder(Order o) {
        orderRepositroy.save(o);
    }

    public void removeOrder(Long orderId) {
        if (orderId == null)
            throw new OrderException("No Order ID!");
        Optional<Order> o = orderRepositroy.findById(orderId);
        if (orderRepositroy.existsById(orderId) == false)
            throw new OrderException("Wrong Order ID!");
        orderRepositroy.deleteById(orderId);
    }

    public void add1Piece(Long orderId) {
        Optional<Order> o = orderRepositroy.findById(orderId);
        if (o.isEmpty())
            throw new OrderException("No Order ID!");
        o.get().setQuantity(o.get().getQuantity()+1);
        orderRepositroy.save(o.get());
    }
}
