package com.utopiaindustries.dao.ctp;

import com.utopiaindustries.model.ctp.FinishedItem;
import com.utopiaindustries.model.ctp.InventoryTransactionLeg;
import com.utopiaindustries.model.ctp.StitchingOfflineItem;
import com.utopiaindustries.util.KeyHolderFunctions;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Repository
public class StitchingOfflineItemDAO {

    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private final String TABLE_NAME = "cut_to_pack.stitching_offline_item";
    private final String SELECT_QUERY = String.format( "SELECT * FROM %s WHERE id = :id", TABLE_NAME );
    private final String SELECT_ALL_QUERY = String.format( "SELECT * FROM %s ORDER BY id DESC", TABLE_NAME );
    private final String SELECT_QUERY_BY_JOB_CARD = String.format( "SELECT * FROM %s WHERE job_card_id = :job_card_id AND inline_received = TRUE", TABLE_NAME );
    private final String DELETE_QUERY = String.format( "DELETE FROM %s WHERE id = :id", TABLE_NAME );
    private final String INSERT_QUERY = String.format( "INSERT INTO %s (id, item_id, sku, barcode, created_at, created_by, job_card_id, is_qa, qa_remarks, qa_status,bundle_id, qc_done_at, inline_received) VALUES (:id, :item_id, :sku, :barcode, :created_at, :created_by, :job_card_id, :is_qa, :qa_remarks, :qa_status, :bundle_id, :qc_done_at, :inline_received) ON DUPLICATE KEY UPDATE item_id = VALUES(item_id), sku = VALUES(sku), barcode = VALUES(barcode), created_at = VALUES(created_at), created_by = VALUES(created_by), job_card_id = VALUES(job_card_id), is_qa = VALUES(is_qa), qa_remarks = VALUES(qa_remarks), qa_status = VALUES(qa_status), bundle_id = VALUES(bundle_id), qc_done_at = VALUES(qc_done_at), inline_received = VALUES(inline_received)", TABLE_NAME );
    private final String SELECT_BY_LIMIT = String.format("SELECT * FROM %s ORDER BY id DESC LIMIT :limit", TABLE_NAME );
    private final String FIND_TOTAL_COUNT = String.format("SELECT COUNT(*) FROM %s  where job_card_id = :job_card_id And item_id = :item_id AND inline_received = TRUE", TABLE_NAME );
    private final String SELECT_BY_IDS = String.format( "SELECT * FROM %s WHERE id IN (:ids)", TABLE_NAME );
    private final String SELECT_BY_TERM = String.format( "SELECT * FROM %s WHERE barcode LIKE :term AND inline_received = TRUE ORDER BY ID DESC", TABLE_NAME );
    private final String SELECT_BY_BUNDLE_ID = String.format( "SELECT * FROM %s WHERE bundle_id = :bundle_id", TABLE_NAME );
    private final String COUNT_TOTAL_QA_ITEMS= String.format("SELECT COUNT(*) FROM %s WHERE job_card_id = :job_card_id AND inline_received = TRUE AND is_qa IS TRUE",TABLE_NAME);
    private final String SELECT_BY_TIME_AND_CARD_ID= String.format("SELECT * FROM %s WHERE job_card_id = :job_card_id AND inline_received = TRUE ORDER BY created_at DESC LIMIT 1;",TABLE_NAME);
    private final String SELECT_BY_JOB_CARD_AND_DATE = String.format( "SELECT * FROM %s WHERE job_card_id = :job_card_id AND inline_received = TRUE AND (:start_date IS NULL OR :end_date IS NULL OR created_at BETWEEN :start_date AND :end_date)", TABLE_NAME );
    private final String SELECT_BY_DATE_QA_STATUS = String.format( "SELECT COUNT(*) FROM %s WHERE (:start_date IS NULL OR qc_done_at >= :start_date) AND inline_received = TRUE AND qc_done_at <= :end_date AND qa_status = :qa_status AND id IN (:ids)", TABLE_NAME );
    private final String SELECT_BY_DATE_QA_STATUS_APPROVED= String.format( "SELECT COUNT(*) FROM %s WHERE (:start_date IS NULL OR qc_done_at >= :start_date) AND inline_received = TRUE AND qc_done_at <= :end_date AND qa_status = :qa_status", TABLE_NAME );

    public StitchingOfflineItemDAO(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    // prepare query params
    private MapSqlParameterSource prepareInsertQueryParams(StitchingOfflineItem stitchingOfflineItem ) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "id", stitchingOfflineItem.getId() )
                .addValue( "item_id", stitchingOfflineItem.getItemId() )
                .addValue( "sku", stitchingOfflineItem.getSku() )
                .addValue( "barcode", stitchingOfflineItem.getBarcode() )
                .addValue("bundle_id",stitchingOfflineItem.getBundleId())
                .addValue( "created_at", stitchingOfflineItem.getCreatedAt() )
                .addValue( "created_by", stitchingOfflineItem.getCreatedBy() )
                .addValue("job_card_id", stitchingOfflineItem.getJobCardId() )
                .addValue("is_qa", stitchingOfflineItem.getIsQa() )
                .addValue("qa_remarks", stitchingOfflineItem.getQaRemarks() )
                .addValue("qc_done_at", stitchingOfflineItem.getQcDoneAt() )
                .addValue("qa_status", stitchingOfflineItem.getQaStatus() )
                .addValue("inline_received", stitchingOfflineItem.isInlineReceived() );
        return params;
    }

    // find
    public StitchingOfflineItem find( long id ) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "id", id );
        return  namedParameterJdbcTemplate.query( SELECT_QUERY, params, new StitchingOfflineItemRowMapper() )
                .stream()
                .findFirst()
                .orElse( new StitchingOfflineItem() );
    }

    // find all
    public List<StitchingOfflineItem> findAll() {
        return namedParameterJdbcTemplate.query( SELECT_ALL_QUERY, new StitchingOfflineItemRowMapper() );
    }

    // save
    public long save( StitchingOfflineItem finishedItem ) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        MapSqlParameterSource params = prepareInsertQueryParams( finishedItem );
        namedParameterJdbcTemplate.update( INSERT_QUERY, params, keyHolder );
        return KeyHolderFunctions.getKey( finishedItem.getId(), keyHolder );
    }

    // save all
    public int[] saveAll( List<StitchingOfflineItem> stitchingOfflineItems ) {
        List<MapSqlParameterSource> batchArgs = new ArrayList<>();
        for ( StitchingOfflineItem stitchingOfflineItem: stitchingOfflineItems ) {
            MapSqlParameterSource params = prepareInsertQueryParams( stitchingOfflineItem );
            batchArgs.add( params );
        }
        return namedParameterJdbcTemplate.batchUpdate( INSERT_QUERY, batchArgs.toArray(new MapSqlParameterSource[stitchingOfflineItems.size()]) );
    }

    // delete
    public boolean delete( long id ) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "id", id );
        return namedParameterJdbcTemplate.update( DELETE_QUERY, params ) > 0;
    }

    public List<StitchingOfflineItem> findByLimit(Long count ){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "limit",count );
        return namedParameterJdbcTemplate.query( SELECT_BY_LIMIT , params, new StitchingOfflineItemRowMapper() );
    }

    public List<StitchingOfflineItem> findByQuery(String query ){
        return namedParameterJdbcTemplate.query( query, new StitchingOfflineItemRowMapper() );
    }

    public List<StitchingOfflineItem> findByIds(List<Long> ids ){
        if( ids == null || ids.isEmpty() ) return new ArrayList<>();
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("ids", ids );
        return namedParameterJdbcTemplate.query( SELECT_BY_IDS , params, new StitchingOfflineItemRowMapper() );
    }

    public List<StitchingOfflineItem> findByJobCardId(long jobCardId){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "job_card_id", jobCardId );
        return namedParameterJdbcTemplate.query( SELECT_QUERY_BY_JOB_CARD , params, new StitchingOfflineItemRowMapper() );
    }

    public List<StitchingOfflineItem> findByTerm( String term  ){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("term", "%" + term + "%" );
    //    params.addValue("is_qa", isQa );
        return namedParameterJdbcTemplate.query( SELECT_BY_TERM , params, new StitchingOfflineItemRowMapper() );
    }

    public List<StitchingOfflineItem> findByBundleId( long bundleId ){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("bundle_id", bundleId );
        return namedParameterJdbcTemplate.query( SELECT_BY_BUNDLE_ID , params, new StitchingOfflineItemRowMapper() );
    }

    public HashMap<Long, Long> findTotalStitchingOfflineItems(List<Long> itemIds, long jobCardId) {
        HashMap<Long, Long> totalCounts = new HashMap<>();
        MapSqlParameterSource params = new MapSqlParameterSource();
        for (long id : itemIds) {
            params.addValue("job_card_id", jobCardId);
            params.addValue("item_id", id);
            Long total = namedParameterJdbcTemplate.queryForObject(FIND_TOTAL_COUNT, params, Long.class);

            if (total != null) {
                totalCounts.put(id, total);
            }
        }
        return totalCounts;
    }

    public Long CalculateTotalQA( long jobCardId ){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("job_card_id", jobCardId );
        Long count = namedParameterJdbcTemplate.queryForObject(COUNT_TOTAL_QA_ITEMS, params, Long.class);
        return count != null ? count : 0;
    }

    public StitchingOfflineItem getLastStitchItemByCardIdAndTime(long jobCardId) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("job_card_id", jobCardId);

        return namedParameterJdbcTemplate.query(SELECT_BY_TIME_AND_CARD_ID, params,new StitchingOfflineItemRowMapper())
                .stream()
                .findFirst()
                .orElse( new StitchingOfflineItem() );
    }

    public List<StitchingOfflineItem> findByJobCardIdAndDate(long jobCardId, String startDate, String endDate){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "job_card_id", jobCardId );
        params.addValue( "start_date", startDate );
        params.addValue( "end_date", endDate );
        return namedParameterJdbcTemplate.query( SELECT_BY_JOB_CARD_AND_DATE , params, new StitchingOfflineItemRowMapper() );
    }

    public Long findByQCOperationDateAndIds(String startDate, String endDate, String qaStatus, List<Long> ids){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "start_date", startDate );
        params.addValue( "end_date", endDate );
        params.addValue( "qa_status", qaStatus );
        params.addValue( "ids", ids);
        Long count = namedParameterJdbcTemplate.queryForObject(SELECT_BY_DATE_QA_STATUS, params, Long.class);
        return count != null ? count : 0;
    }
    public Long findByQCOperationDateAndApproved(String startDate, String endDate, String qaStatus){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "start_date", startDate );
        params.addValue( "end_date", endDate );
        params.addValue( "qa_status", qaStatus );
        Long count = namedParameterJdbcTemplate.queryForObject(SELECT_BY_DATE_QA_STATUS_APPROVED, params, Long.class);
        return count != null ? count : 0;
    }
}
