package org.exoplatform.cs.job;

import org.exoplatform.container.ExoContainer;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.cs.entity.StatLogEntity;
import org.exoplatform.cs.service.StatsService;
import org.exoplatform.cs.service.TicketService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.List;

/**
 * Created by eXo Platform SAS.
 *
 * @author Ali Hamdi 
 * @since 23/08/17 17:39
 */

public class StatsCollectorJob implements Job {
  private static final Logger LOG = LoggerFactory.getLogger(StatsCollectorJob.class);



  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    ExoContainer containerContext = ExoContainerContext.getCurrentContainer();
    StatsService statsService = containerContext.getComponentInstanceOfType(StatsService.class);
    TicketService ticketService = containerContext.getComponentInstanceOfType(TicketService.class);

    Calendar now = Calendar.getInstance();
    boolean weekly = false;
    boolean monthly = false;
     if(now.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY) weekly=true;
    if(now.get(Calendar.DAY_OF_MONTH)==now.getActualMaximum(Calendar.DAY_OF_MONTH)) monthly=true;
    LOG.info("Start getting satats");
    Long closed =ticketService.getCustomerClosedTicketsCount(false);
    Long opened =ticketService.getCustomerOpenTicketsCount(false);
    StatLogEntity closedStat = new StatLogEntity();
    closedStat.setStatDate(now);
    closedStat.setStatType("closedTikets");
    closedStat.setStatus("closed");
    closedStat.setTicketsNumber(closed);
    closedStat.setWeekly(weekly);
    closedStat.setMonthly(monthly);
    closedStat.setSpaceId("");
    statsService.save(closedStat);

    StatLogEntity openedStat = new StatLogEntity();
    openedStat.setStatDate(now);
    openedStat.setStatType("openedTikets");
    openedStat.setStatus("opened");
    openedStat.setTicketsNumber(opened);
    openedStat.setWeekly(weekly);
    openedStat.setMonthly(monthly);
    openedStat.setSpaceId("");
    statsService.save(openedStat);


    List<Object[]> results =ticketService.countCustomerTicketsGroupdByStatus(false);

    for (int i = 0; i < results.size(); i++) {
        StatLogEntity stat = new StatLogEntity();
      Object[] arr = results.get(i);
      stat.setStatDate(now);
      stat.setStatType("tiketsByStatus");
      stat.setStatus(((String) arr[0]).toString());
      stat.setTicketsNumber((Long)arr[1]);
      stat.setWeekly(weekly);
      stat.setMonthly(monthly);
      stat.setSpaceId("");
      statsService.save(stat);
    }
    LOG.info("Stats collecting finished");


  }

}
