package com.nisum.myteam.status.service;

import com.itextpdf.styledxmlparser.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nisum.myteam.status.exceptions.EmployeeNotFoundException;
import com.nisum.myteam.status.model.Status;
import com.nisum.myteam.status.repository.StatusRepository;
import com.nisum.myteam.status.repository.StatusRepositoryImpl;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class StatusServiceImpl implements StatusService {

  private static final Logger LOGGER = LoggerFactory.getLogger(StatusServiceImpl.class);

  @Autowired
  private StatusRepository repository;

  @Autowired
  private SequenceGeneratorService sequenceGeneratorService;

  @Autowired
  private StatusRepositoryImpl statusRepositoryImpl;

  /**
   * Save the task details
   * @param status
   * @return
   */
  public Status saveStatusDetails(Status status) {
    Optional<Status> s = Optional.ofNullable(status);
    if(s.isPresent()){
      status.setId((int) sequenceGeneratorService.generateSequence(Status.SEQUENCE_NAME));
      if(StringUtil.isBlank(status.getTicketNumber())){
        status.setTicketNumber("NA");
      }
      if(StringUtil.isBlank(status.getHoursSpent())){
        status.setHoursSpent("NA");
      }
      if(StringUtil.isBlank(status.getTaskDetails())){
        status.setTaskDetails("NA");
      }
      if(StringUtil.isBlank(status.getPriority())){
        status.setPriority("NA");
      }
      if(StringUtil.isBlank(status.getTaskType())){
        status.setTaskType("NA");
      }
      if(StringUtil.isBlank(status.getStatus())){
        status.setStatus("NA");
      }
    }
    Status saveStatus = s.get();
    LOGGER.info("Request for saving task details : "+saveStatus);
    return repository.save(saveStatus);
  }

  /**
   * Get the today task details based on employee ID and today date
   * @param empId
   * @return
   */
  public List<Status> findTodayStatus(String empId){
    LocalDate today = LocalDate.now();
    List<Status> status = null;
    try{
      if(empId != null){
        status = statusRepositoryImpl.findTodayStatus(empId, today);
      }
    }
    catch(Exception e){
      throw e;
    }
    return status;
  }

  /**
   * Find task details by task date and employee id
   * @param empId
   * @param date
   * @return status
   */
  public List<Status> findTaskDataByTaskDate(String empId, LocalDate date){
    List<Status> status = null;
    try{
      if(!StringUtil.isBlank(empId) && date != null){
        status = statusRepositoryImpl.findTodayStatus(empId, date);
        //Query query = new Query().addCriteria(Criteria.where("empId").is(empId).and("taskDate").is(date));
        //status =  mongoTemplate.find(query, Status.class);
      }
    }
    catch(Exception e){
      throw e;
    }
    return status;
  }

  /**
   * Fetch the task details based on employee ID
   * @param empId
   * @return
   */
  public List<Status> getStatusDetailsByEmpId(String empId){
    try{
      return statusRepositoryImpl.findByempId(empId);
    }catch(Exception e){
      throw e;
    }
  }

  /**
   * Fetch the task details based on date range(fromDate to toDate)
   * @param fromDate
   * @param toDate
   * @param empId
   * @return
   */
  public List<Status> getByDateRange(LocalDate fromDate, LocalDate toDate, String empId){
    try{
      return statusRepositoryImpl.findByDateRange(fromDate, toDate, empId);
    }catch(Exception e){
      throw e;
    }
  }

  /**
   * Find the all employees task details
   * @return
   */
  public List<Status> getEmployeeStatusDetails() {
    try{
      return repository.findAll();
    }
    catch(Exception e){
      throw e;
    }
  }

  /**
   * Update the task details based on task ID
   * @param status
   * @return
   */
  public Status updateStatusDetails(Status status) {
    Optional<Status> optionalStatus = repository.findById(status.getId());
    if (optionalStatus.isPresent()) {
      Status updatedStatus = optionalStatus.get();
      updatedStatus.setTaskType(status.getTaskType());
      updatedStatus.setTaskDate(status.getTaskDate());
      updatedStatus.setStoryPoints(status.getStoryPoints());
      updatedStatus.setHoursSpent(status.getHoursSpent());
      updatedStatus.setTicketNumber(status.getTicketNumber());
      updatedStatus.setPriority(status.getPriority());
      updatedStatus.setPlanedStartDate(status.getPlanedStartDate());
      updatedStatus.setPlanedEndDate(status.getPlanedEndDate());
      updatedStatus.setActualStartDate(status.getActualStartDate());
      updatedStatus.setActualEndDate(status.getActualEndDate());
      updatedStatus.setComments(status.getComments());
      updatedStatus.setStatus(status.getStatus());
      updatedStatus.setTaskDetails(status.getTaskDetails());
      repository.save(updatedStatus);
      return updatedStatus;
    } else {
      throw new EmployeeNotFoundException(status.getId());
    }
  }

  /**
   * Delete the task details based on task ID
   * @param id
   */
  public void deleteEmployeeStatusDetails(Integer id){
    try{
      if(repository.existsById(id)){
        repository.deleteById(id);
      }
    }catch(Exception e){
      throw e;
    }
  }

  /**
   * fetch the last five dates records based on employee ID
   * @param empId
   * @return
   */
  public List<Status> getDefaultStatusDetails(String empId) {
    try{
      List<Status> status = statusRepositoryImpl.findByLastFiveDays(empId);
      LOGGER.info("Response for last five dates task details : "+status);
      return status;
    }catch(Exception e){
      throw e;
    }
  }

}
