package com.utopiaindustries.service;

import com.utopiaindustries.dao.ctp.JobCardDAO;
import com.utopiaindustries.dao.ctp.PurchaseOrderCTPDao;
import com.utopiaindustries.dao.ctp.StoreItemDao;
import com.utopiaindustries.model.ctp.*;
import com.utopiaindustries.model.uind.PurchaseOrder;
import com.utopiaindustries.querybuilder.ctp.JobCardQueryBuilder;
import com.utopiaindustries.querybuilder.ctp.PurchaseOrderCTPQueryBuilder;
import com.utopiaindustries.util.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PurchaseOrderCTPService {

    private final PurchaseOrderCTPDao purchaseOrderCTPDao;
    private final JobCardDAO jobCardDAO;
    private final StoreItemDao storeItemDao;

    public PurchaseOrderCTPService(PurchaseOrderCTPDao purchaseOrderCTPDao, JobCardDAO jobCardDAO, StoreItemDao storeItemDao) {
        this.purchaseOrderCTPDao = purchaseOrderCTPDao;
        this.jobCardDAO = jobCardDAO;
        this.storeItemDao = storeItemDao;
    }

    /*
     * search by id
     * */
    public PurchaseOrderCTP searchPurchaseOrderById(long id){
        return purchaseOrderCTPDao.find(id);
    }

    /*
     *  create new purchase
     * */
    public PurchaseOrderCTP createNewPurchaseOrderCTP() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        PurchaseOrderCTP purchaseOrderCTP = new PurchaseOrderCTP();
        purchaseOrderCTP.setCreatedBy( authentication.getName() );
        purchaseOrderCTP.setCreatedAt( LocalDateTime.now() );
        return purchaseOrderCTP;
    }

    /*
     *  save purchase order for ctp
     * */
    @Transactional( rollbackFor = Exception.class )
    public void save(PurchaseOrderCTP purchaseOrderCTP) {
        purchaseOrderCTPDao.save(purchaseOrderCTP);
    }

    public List<PurchaseOrderCTP> getAllPurchaseOrderCtp(String purchaseOrderCode, String articleName, String startDate, String endDate, Long limit) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<PurchaseOrderCTP> list = new ArrayList<>();
        String createdBy = authentication.getName();
        if( limit == null ){
            limit = 100L;
        }
        if(StringUtils.isAnyNotNullOrEmpty(purchaseOrderCode, articleName,startDate,endDate) ){
            for (GrantedAuthority role : authentication.getAuthorities()){
                if (role.toString().equals("ROLE_ADMIN")){
                    createdBy = "";
                }
            }
            String query = PurchaseOrderCTPQueryBuilder.buildQuery(purchaseOrderCode, articleName, createdBy, startDate, endDate, limit );
                    System.out.println( query );
            list = purchaseOrderCTPDao.findByQuery( query );
        }else {
            list = purchaseOrderCTPDao.findByUserAndLimit( authentication.getName(), limit );
        }
        return list;
    }

    public List<PurchaseOrderCTP> findByTerm(String term ){
        return purchaseOrderCTPDao.findByTerm( term );
    }

    public Map<String,Integer> getStoreItemsByPoId(Long poId){
        Map<String,Integer> totalItems = new HashMap<>();
        List<JobCard> jobCards = jobCardDAO.findByPoId(poId);
        List<Long> jobCardIds = jobCards.stream()
                .map(JobCard::getId)
                .collect(Collectors.toList());
        if(!jobCardIds.isEmpty()){
            return storeItemDao.totalCountByJobCardIdsAndGroupByRejectReason(jobCardIds);
        }else {
            return totalItems;
        }
    }

}
