package com.utopiaindustries.dao.ctp;

import com.utopiaindustries.model.ctp.JobCard;
import com.utopiaindustries.util.KeyHolderFunctions;
import org.springframework.beans.factory.annotation.Autowired;
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 JobCardDAO {

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final String TABLE_NAME = "cut_to_pack.job_card";
	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_ALL_BY_PO_ID = String.format( "SELECT * FROM %s WHERE purchase_order_id = :purchase_order_id", 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, code, job_order_id, created_at, created_by, status, inventory_status, customer, lot_number, purchase_order_id, location_site_id, description, poQuantity, articleName) VALUES (:id, :code, :job_order_id, :created_at, :created_by, :status, :inventory_status, :customer, :lot_number, :purchase_order_id, :location_site_id, :description, :poQuantity, :articleName) ON DUPLICATE KEY UPDATE code = VALUES(code), job_order_id = VALUES(job_order_id), created_at = VALUES(created_at), created_by = VALUES(created_by), status = VALUES(status), inventory_status = VALUES(inventory_status), customer = VALUES(customer), lot_number = VALUES(lot_number), purchase_order_id = VALUES(purchase_order_id), location_site_id = VALUES(location_site_id), description = VALUES(description), poQuantity = VALUES(poQuantity), articleName = VALUES(articleName) ", TABLE_NAME );
	private final String SELECT_BY_LIKE_CODE_AND_INV_STATUS_AND_STATUS = String.format( "SELECT * FROM %s WHERE code like :code AND status = :status AND inventory_status = :inventory_status", TABLE_NAME );
	private final String SELECT_BY_LIKE_CODE = String.format( "SELECT * FROM %s WHERE code like :code", TABLE_NAME );
	private final String SELECT_BY_LIKE_CODE_AND_PO_ID = String.format( "SELECT * FROM %s WHERE code like :code AND purchase_order_id = :purchase_order_id", TABLE_NAME );
	private final String SELECT_BY_LIMIT = String.format( "SELECT * FROM %s WHERE created_by = :created_by ORDER BY id ASC limit :limit", TABLE_NAME );

	// prepare query params
	private MapSqlParameterSource prepareInsertQueryParams( JobCard jobCard ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", jobCard.getId() )
			.addValue("code", jobCard.getCode() )
			.addValue( "job_order_id", jobCard.getJobOrderId() )
			.addValue( "created_at", jobCard.getCreatedAt() )
			.addValue( "created_by", jobCard.getCreatedBy() )
			.addValue("status", jobCard.getStatus() )
			.addValue("inventory_status", jobCard.getInventoryStatus() )
			.addValue("customer", jobCard.getCustomer() )
			.addValue("poQuantity", jobCard.getPoQuantity() )
			.addValue("articleName", jobCard.getArticleName() )
			.addValue("lot_number", jobCard.getLotNumber() )
			.addValue("purchase_order_id", jobCard.getPurchaseOrderId() )
			.addValue("location_site_id", jobCard.getLocationSiteId() )
			.addValue("description", jobCard.getDescription() );
		return params;
	}

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


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

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

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

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

	public List<JobCard> findLikeCode( String code ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("code", "%" + code + "%");
		return namedParameterJdbcTemplate.query(SELECT_BY_LIKE_CODE, params, new JobCardRowMapper());
	}

	public List<JobCard> findLikeCodeAndPoID( String code, long poID ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("code", "%" + code + "%");
		params.addValue("purchase_order_id", poID);
		return namedParameterJdbcTemplate.query(SELECT_BY_LIKE_CODE_AND_PO_ID, params, new JobCardRowMapper());
	}

	public List<JobCard> findLikeCode( String code , String inventoryStatus, String status ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "code", "%" + code + "%" );
		params.addValue("inventory_status", inventoryStatus );
		params.addValue("status", status );
		return namedParameterJdbcTemplate.query(SELECT_BY_LIKE_CODE_AND_INV_STATUS_AND_STATUS, params, new JobCardRowMapper() );
	}

	public List<JobCard> findByUserAndLimit( String createdBy, Long limit ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("limit", limit.intValue() );
		params.addValue("created_by", createdBy );
		return namedParameterJdbcTemplate.query( SELECT_BY_LIMIT, params, new JobCardRowMapper() );
	}

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

	public List<JobCard> findByPoId(long poId){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("purchase_order_id", poId);
		return namedParameterJdbcTemplate.query( SELECT_ALL_BY_PO_ID, params, new JobCardRowMapper() );
	}
}