package com.utopiaindustries.dao.ctp;

import com.utopiaindustries.model.ctp.Bundle;
import com.utopiaindustries.util.KeyHolderFunctions;
import com.utopiaindustries.util.StringUtils;
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 BundleDAO {

	private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final String TABLE_NAME = "cut_to_pack.bundle";
	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 INSERT_QUERY = String.format( "INSERT INTO %s (id, item_id, sku, wrap_quantity, barcode, type, created_by, created_at, job_card_id, master_bundle_id) VALUES (:id, :item_id, :sku, :wrap_quantity, :barcode, :type, :created_by, :created_at, :job_card_id, :master_bundle_id) ON DUPLICATE KEY UPDATE item_id = VALUES(item_id), sku = VALUES(sku), wrap_quantity = VALUES(wrap_quantity), barcode = VALUES(barcode), type = VALUES(type), created_by = VALUES(created_by), created_at = VALUES(created_at), job_card_id = VALUES(job_card_id), master_bundle_id = VALUES(master_bundle_id)", TABLE_NAME );
	private final String SELECT_BY_TERM_QUERY = String.format( "SELECT * FROM %s WHERE (id = :id OR sku LIKE :sku OR type LIKE :type OR barcode LIKE :barcode) AND master_bundle_id =0", TABLE_NAME );
	private final String SELECT_BY_LIMIT = String.format( "SELECT * FROM %s ORDER BY id DESC LIMIT :limit", TABLE_NAME );
	private final String SELECT_BY_MASTER_ID = String.format( "SELECT * FROM %s WHERE master_bundle_id = :master_bundle_id ORDER BY id DESC", TABLE_NAME );
	private final String SELECT_BY_IDS = String.format( "SELECT * FROM %s WHERE id IN (:ids)", TABLE_NAME );
	private final String SELECT_BY_ITEM_ID_AND_JOB_CARD = String.format( "SELECT * FROM %s WHERE item_id = :item_id AND job_card_id = :job_card_id", TABLE_NAME );
	private final String SELECT_BY_ITEM_IDS_AND_JOB_CARD = String.format( "SELECT * FROM %s WHERE item_id IN (:item_ids) AND job_card_id = :job_card_id", TABLE_NAME );


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

	// prepare query params
	private MapSqlParameterSource prepareInsertQueryParams( Bundle bundle ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", bundle.getId() )
			.addValue( "item_id", bundle.getItemId() )
			.addValue( "sku", bundle.getSku() )
			.addValue( "wrap_quantity", bundle.getWrapQuantity() )
			.addValue( "barcode", bundle.getBarcode() )
			.addValue( "type", bundle.getType() )
			.addValue( "created_by", bundle.getCreatedBy() )
			.addValue( "created_at", bundle.getCreatedAt() )
			.addValue( "job_card_id", bundle.getJobCardId() )
			.addValue( "master_bundle_id", bundle.getMasterBundleId() );
		return params;
	}

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

	}

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

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

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

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

	public List<Bundle> findByTerm( String term ){
		if( StringUtils.isNullOrEmpty( term ) ) return new ArrayList<>();
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id",term );
		params.addValue( "sku","%" + term + "%" );
		params.addValue( "type","%" + term + "%" );
		params.addValue("barcode", "%" + term + "%" );
		return namedParameterJdbcTemplate.query( SELECT_BY_TERM_QUERY, params , new BundleRowMapper() );
	}

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

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

	public List<Bundle> findByMasterId( long masterId ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("master_bundle_id", masterId );
		return namedParameterJdbcTemplate.query( SELECT_BY_MASTER_ID, params, new BundleRowMapper() );
	}

	public List<Bundle> 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 BundleRowMapper() );
	}

	public List<Bundle> findByItemIdAndCardId( long itemId, long cardId ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("item_id", itemId );
		params.addValue("job_card_id", cardId );
		return namedParameterJdbcTemplate.query( SELECT_BY_ITEM_ID_AND_JOB_CARD, params, new BundleRowMapper() );
	}

	public List<Bundle> findByItemIdsAndCardId( List<Long> itemIds, long cardId ){
		if( itemIds == null || itemIds.isEmpty() ) return new ArrayList<>();
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("item_ids", itemIds );
		params.addValue("job_card_id", cardId );
		return namedParameterJdbcTemplate.query( SELECT_BY_ITEM_IDS_AND_JOB_CARD, params, new BundleRowMapper() );
	}
}