package kundedb.service;

import kundedb.models.Produkt;
import models.CustomerModel;
import models.OrderModel;
import models.OrderStatus;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.CustomerService;
import service.OrderService;
import service.PoseidonPropertyService;
import service.PoseidonService;

import java.util.List;

public class KundedbService extends PoseidonService {

  private final static Logger logger = LoggerFactory.getLogger(KundedbService.class);

  private final OrderService orderService = new OrderService("akka");
  private final CustomerService customerService = new CustomerService("akka");
  private final KundedbSyncer syncer = new KundedbSyncer();

  public KundedbService(String user) {
    super(user);
  }

  public KundedbSyncSummary syncKundedb() {
    logger.info("Starter kundedb.service.KundedbService.syncKundedb");
    DateTime today = new DateTime(getToday(), getTimeZone()).withTimeAtStartOfDay();
    //DateTime tomorrow = today.plusDays(1);
    DateTime yesterday = today.minusDays(1);

    KundedbSyncSummary summary = new KundedbSyncSummary();

    // Sync customers
    List<CustomerModel> customers = customerService.findNewOrUpdatedCustomersSince(yesterday);
    if (customers != null && customers.size() > 0) {
      for (CustomerModel customer : customers) {
        logger.info("syncer kunde {}", customer.name);
        syncer.syncCustomer(customer);
      }
      summary.syncedCustomers = customers.size();
    }


    // Delete inactive orders
    List<OrderModel> inactiveOrders = orderService.getInactiveOrdersForKundedb();
    summary.deletedOrders = 0;
    if (inactiveOrders != null && inactiveOrders.size() > 0) {
      for (OrderModel order : inactiveOrders) {
        logger.info("Sletter kundefil and datafil for ordre {}", order.id);
        summary.deletedOrders += syncer.deleteKundefiler(order.id);
        syncer.deleteDatafil(order.id);
      }
    }

    // Sync orders
    List<OrderModel> orders = orderService.getActiveOrdersForKundedb();
    if (orders != null && orders.size() > 0) {
      String produktnavn = PoseidonPropertyService.getProperty("kundedb.produkt");
      Produkt produkt = Produkt.findByName(produktnavn);
      if (produkt != null) {
        for (OrderModel order : orders) {
          syncer.syncOrder(order, produkt);
        }
        summary.syncedOrders = orders.size();
      } else {
        logger.warn("Kundedb produkt med navn {} ikke funnet i kundedb. Synking av ordre ikke utført", produktnavn);
      }
    }
    logger.info("kundedb.service.KundedbService.syncKundedb er ferdig: {}", summary);

    return summary;
  }

  public void syncKundeImmediately(CustomerModel customerModel) {
    logger.info("Starter kundedb.service.KundedbService.syncKundeImmediately");
    syncer.syncCustomer(customerModel);

  }

  public void syncOrderImmediately(OrderModel orderModel) {

    logger.info("Starter kundedb.service.KundedbService.syncOrderImmediately for ordre med namn: {}", orderModel.position_name);

    String produktnavn = PoseidonPropertyService.getProperty("kundedb.produkt");
    Produkt produkt = Produkt.findByName(produktnavn);

    if (produkt == null) {
      logger.error("Kundedb produkt med navn {} ikke funnet i kundedb. Synking av ordre ikke utført", produktnavn);
      //throw new PoseidonException(Http.Status.INTERNAL_SERVER_ERROR,"Fant ikke KundeDB produkt " + produktnavn);
      return;
    }


    DateTime now = new DateTime(PoseidonService.getTimeZone());
    DateTime today = now.withTimeAtStartOfDay();
    DateTime tomorrow = today.plusDays(1);


    DateTime start1 = new DateTime(orderModel.start_date1, PoseidonService.getTimeZone()).withTimeAtStartOfDay();
    DateTime start2 = null;
    if (orderModel.start_date2 != null) {
      start2 = new DateTime(orderModel.start_date2, PoseidonService.getTimeZone()).withTimeAtStartOfDay();
    }

    DateTime start3 = null;
    if (orderModel.start_date3 != null) {
      start3 = new DateTime(orderModel.start_date3, PoseidonService.getTimeZone()).withTimeAtStartOfDay();
    }


    if (orderModel.orderStatus == OrderStatus.ACTIVE) {
      syncer.syncOrder(orderModel, produkt);
    } else if (start2 != null && start2.isEqual(today)) {
      syncer.syncOrder(orderModel, produkt);
    } else if (start1.isEqual(today)) {
      syncer.syncOrder(orderModel, produkt);
    } else {
      String startHourProp = PoseidonPropertyService.getProperty("kundedbsync.start_hour");
      int startHour = Integer.valueOf(startHourProp);

      if (now.getHourOfDay() >= startHour) {

        if (start3 != null && start3.isEqual(tomorrow)) {
          syncer.syncOrder(orderModel, produkt);
        } else if (start2 != null && start2.isEqual(tomorrow)) {
          syncer.syncOrder(orderModel, produkt);
        } else if (start1.isEqual(tomorrow)) {
          syncer.syncOrder(orderModel, produkt);
        }
      }
    }
  }
}
