package org.hso.ecommerce.action.user;

import org.hso.ecommerce.api.RestServiceForDelivery;
import org.hso.ecommerce.entities.shop.CustomerOrder;
import org.hso.ecommerce.repos.shop.CustomerOrderRepository;
import org.hso.ecommerce.uimodel.DeliveryData;
import org.hso.ecommerce.uimodel.DeliveryDataEnum;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CreateDeliveryData {

    public static DeliveryData getDeliveryDataFromCustomerOrder(CustomerOrder customerOrder, CustomerOrderRepository customerOrderRepository, RestServiceForDelivery restServiceForDelivery)
    {
        if(customerOrder.trackingId == null)
            return new DeliveryData("", "", DeliveryDataEnum.NO_TRACKING_ID);

        if(customerOrder.deliveredAt == null)
        {
            DeliveryData deliveryData = restServiceForDelivery.getDeliveryData(customerOrder.trackingId);


            if(deliveryData.isDelivered())
            {
                Calendar calendar = Calendar.getInstance();

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

                try {
                    calendar.setTime(simpleDateFormat.parse(deliveryData.getEstimatedArrival()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                customerOrder.deliveredAt = new Timestamp(calendar.getTimeInMillis());
                customerOrderRepository.save(customerOrder);
            }

            return deliveryData;
        }

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        return new DeliveryData("Lieferung erfolgreich", formatter.format(customerOrder.deliveredAt), DeliveryDataEnum.OK);
    }
}
