package com.utopiaindustries.dao.ctp;

import com.utopiaindustries.model.ctp.JobCardItem;
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 JobCardItemDAO {

	private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final String TABLE_NAME = "cut_to_pack.job_card_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 DELETE_QUERY = String.format( "DELETE FROM %s WHERE id = :id", TABLE_NAME );
	private final String SELECT_BY_CARD_ID = String.format( "SELECT * FROM %s WHERE job_card_id = :card_id", TABLE_NAME );
	private final String SELECT_BY_CARD_ID_AND_ITEM_ID = String.format( "SELECT * FROM %s WHERE job_card_id = :card_id AND item_id = :item_id ", TABLE_NAME );
	private final String INSERT_QUERY = String.format( "INSERT INTO %s (id, job_card_id, item_id, sku, expected_production, actual_production, total_production, account_id, length, width, gsm, wt_ply, ply, is_complete, size, color) VALUES (:id, :job_card_id, :item_id, :sku, :expected_production, :actual_production, :total_production, :account_id, :length, :width, :gsm, :wt_ply, :ply, :is_complete, :size, :color) ON DUPLICATE KEY UPDATE job_card_id = VALUES(job_card_id), item_id = VALUES(item_id), sku = VALUES(sku), expected_production = VALUES(expected_production), actual_production = VALUES(actual_production), total_production = VALUES(total_production), account_id = VALUES(account_id), length = VALUES(length), width = VALUES(width),  gsm = VALUES(gsm),  wt_ply = VALUES(wt_ply),  ply = VALUES(ply), is_complete = VALUES(is_complete), size =VALUES(size), color =VALUES(color) ", TABLE_NAME );
	private final String SELECT_BY_IDS = String.format( "SELECT * FROM %s WHERE id IN (:ids)", TABLE_NAME );
	private final String SELECT_BY_JOB_CARD_AND_ACCOUNT_IDS = String.format( "SELECT * FROM %s WHERE job_card_id = :job_card_id AND account_id IN (:account_ids) AND is_complete = FALSE ", TABLE_NAME );
	private final String SELECT_ALL_ACTIVE_ITEM = String.format("SELECT CASE WHEN MIN(is_complete) = TRUE THEN TRUE ELSE FALSE END FROM  %s WHERE job_card_id = :job_card_id AND id IN (:id)", TABLE_NAME);
	private final String SELECT_BY_JOB_CARD_IDS_AND_COLOR_SIZE = String.format(
			"SELECT * FROM %s WHERE job_card_id IN (:job_card_id) ",
			TABLE_NAME
	);
	private final String SELECT_ALL_SIZE_GROUP_BY = String.format( "SELECT size FROM %s GROUP BY size", TABLE_NAME );
	private final String SELECT_ALL_COLOR_GROUP_BY = String.format( "SELECT color FROM %s GROUP BY color", TABLE_NAME );

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

	// prepare query params
	private MapSqlParameterSource prepareInsertQueryParams( JobCardItem jobCardItem ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", jobCardItem.getId() )
			.addValue( "job_card_id", jobCardItem.getJobCardId() )
			.addValue( "item_id", jobCardItem.getItemId() )
			.addValue( "sku", jobCardItem.getSku() )
			.addValue( "expected_production", jobCardItem.getExpectedProduction() )
			.addValue("actual_production", jobCardItem.getActualProduction() )
			.addValue("total_production", jobCardItem.getTotalProduction() )
			.addValue("account_id", jobCardItem.getAccountId() )
			.addValue("length", jobCardItem.getLength() )
			.addValue("width", jobCardItem.getWidth() )
			.addValue("gsm", jobCardItem.getGsm() )
			.addValue("wt_ply", jobCardItem.getWtPly() )
			.addValue("ply", jobCardItem.getPly() )
			.addValue("size", jobCardItem.getSize() )
			.addValue("color", jobCardItem.getColor() )
			.addValue("is_complete", jobCardItem.isComplete() );

		return params;
	}

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

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

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

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

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

	public List<JobCardItem> findByCardId( long cardId ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "card_id", cardId );
		return namedParameterJdbcTemplate.query(SELECT_BY_CARD_ID, params, new JobCardItemRowMapper() );
	}

	public JobCardItem findByCardIdAndItemId( long cardId,long itemItem ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "card_id", cardId );
		params.addValue("item_id",itemItem);
		return namedParameterJdbcTemplate.query(SELECT_BY_CARD_ID_AND_ITEM_ID, params, new JobCardItemRowMapper() ).stream()
				.findFirst()
				.orElse( new JobCardItem() );
	}

	public List<JobCardItem> findByIds( List<Long> ids ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "ids", ids );
		return namedParameterJdbcTemplate.query( SELECT_BY_IDS, params, new JobCardItemRowMapper() );
	}

	public List<JobCardItem> findByJobCardAndAccountIdsAndIsReceived( Long jobCardId, List<Long> accountIds ){
		if( accountIds == null || accountIds.isEmpty() ) return new ArrayList<>();
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "account_ids", accountIds );
		params.addValue("job_card_id", jobCardId );
		return namedParameterJdbcTemplate.query( SELECT_BY_JOB_CARD_AND_ACCOUNT_IDS , params, new JobCardItemRowMapper() );
	}

	public boolean checkAllItemsComplete( Long jobCardId, List<Long> itemsId ){
		if( itemsId == null || itemsId.isEmpty() ) return false;
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", itemsId );
		params.addValue("job_card_id", jobCardId );
		Boolean allComplete = namedParameterJdbcTemplate.queryForObject(SELECT_ALL_ACTIVE_ITEM, params, Boolean.class);
		return Boolean.TRUE.equals(allComplete);
	}

	//find By jobCard ids, color and size
	public List<JobCardItem> findByJobCardIdsAndSizeColor(List<Long> ids, String size, String color){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("job_card_id", ids);
		StringBuilder sql = new StringBuilder(SELECT_BY_JOB_CARD_IDS_AND_COLOR_SIZE);
		if (color != null && !color.isEmpty() && !"null".equalsIgnoreCase(color)) {
			sql.append(" AND color = :color");
			params.addValue("color", color);
		}

		if (size != null && !size.isEmpty() && !"null".equalsIgnoreCase(size)) {
			sql.append(" AND size = :size");
			params.addValue("size", size);
		}
		return namedParameterJdbcTemplate.query( sql.toString(), params, new JobCardItemRowMapper() );
	}

	public List<String> getAllSize() {
		return namedParameterJdbcTemplate.queryForList(SELECT_ALL_SIZE_GROUP_BY, new HashMap<>(), String.class);
	}

	public List<String> getAllColor() {
		return namedParameterJdbcTemplate.queryForList(SELECT_ALL_COLOR_GROUP_BY, new HashMap<>(), String.class);
	}

}