package com.utopiaindustries.service;

import com.utopiaindustries.dao.ctp.PurchaseOrderCTPDao;
import com.utopiaindustries.model.ctp.*;
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.List;

@Service
public class PurchaseOrderCTPService {

    private final PurchaseOrderCTPDao purchaseOrderCTPDao;

    public PurchaseOrderCTPService(PurchaseOrderCTPDao purchaseOrderCTPDao) {
        this.purchaseOrderCTPDao = purchaseOrderCTPDao;
    }

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

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

    /*
     *  save card
     * */
    @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) ){
            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;
    }

}
