package com.utopiaindustries.dao.ctp;

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

@Repository
public class CutPieceDAO {

	private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final String TABLE_NAME = "cut_to_pack.cut_piece";
	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_ITEM_IDS = String.format( "SELECT * FROM %s WHERE job_card_item_id IN (:item_ids)", TABLE_NAME );
	private final String SELECT_BY_ITEM_IDS_AND_GROUP_BY = String.format( "SELECT  id,job_card_item_id,`type`,SUM(quantity) AS quantity FROM %s WHERE job_card_item_id IN (:item_ids) GROUP BY job_card_item_id, `type`", TABLE_NAME );
	private final String INSERT_QUERY = String.format( "INSERT INTO %s (id, job_card_item_id, `type`, quantity) VALUES (:id, :job_card_item_id, :type, :quantity) ON DUPLICATE KEY UPDATE job_card_item_id = VALUES(job_card_item_id), `type` = VALUES(`type`), quantity = VALUES(quantity)", TABLE_NAME );
	private final String DELETE_BY_ITEM_ID = String.format( "DELETE FROM %s WHERE job_card_item_id = :job_card_item_id", TABLE_NAME );

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

	// prepare query params
	private MapSqlParameterSource prepareInsertQueryParams( CutPiece cutPiece ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", cutPiece.getId() )
			.addValue( "job_card_item_id", cutPiece.getJobCardItemId() )
			.addValue( "type", cutPiece.getType() )
			.addValue( "quantity", cutPiece.getQuantity() );
		return params;
	}

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

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

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

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

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

	public List<CutPiece> findByJobCardItemIds( List<Long> itemIds ){
		if( itemIds == null || itemIds.isEmpty() )
			return new ArrayList<>();
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("item_ids", itemIds );
		return namedParameterJdbcTemplate.query(SELECT_BY_ITEM_IDS, params, new CutPieceRowMapper() );
	}

	public List<CutPiece> findByJobCardItemIdsWithGroupByType( List<Long> itemIds ){
		if( itemIds == null || itemIds.isEmpty() )
			return new ArrayList<>();
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("item_ids", itemIds );
		return namedParameterJdbcTemplate.query(SELECT_BY_ITEM_IDS_AND_GROUP_BY, params, new CutPieceRowMapper() );
	}

	public boolean deleteByItemId( long jobCardItemId ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("job_card_item_id", jobCardItemId );
		return namedParameterJdbcTemplate.update( DELETE_BY_ITEM_ID , params ) > 0;
	}
}