package com.utopiaindustries.dao.ctp;

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

	private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final String TABLE_NAME = "cut_to_pack.inventory_account";
	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 title 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, title, parent_entity_type, parent_entity_id, active, created_by, created_at, location_site_id, notes, is_packaging) VALUES (:id, :title, :parent_entity_type, :parent_entity_id, :active, :created_by, :created_at, :location_site_id, :notes, :is_packaging) ON DUPLICATE KEY UPDATE title = VALUES(title), parent_entity_type = VALUES(parent_entity_type), parent_entity_id = VALUES(parent_entity_id), active = VALUES(active), created_by = VALUES(created_by), created_at = VALUES(created_at), location_site_id = VALUES(location_site_id), notes = VALUES(notes), is_packaging = VALUES(is_packaging)", TABLE_NAME );
	private final String SELECT_BY_IDS =  String.format( "SELECT * FROM %s WHERE id IN (:ids)", TABLE_NAME );
	private final String SELECT_BY_IDS_AND_PARENT_ID = String.format( "SELECT * FROM %s WHERE active = TRUE AND id IN (:ids) AND parent_entity_id = :parent_entity_id", TABLE_NAME );
	private final String SELECT_BY_IDS_AND_PARENT_IDS = String.format( "SELECT * FROM %s WHERE active = TRUE AND id IN (:ids) AND parent_entity_id IN (:parent_entity_ids)", TABLE_NAME );
	private final String SELECT_BY_IDS_AND_PARENT_ENTITY_TYPE_AND_PARENT_ID_AND_COUNT = String.format( "SELECT * FROM %s WHERE id IN (:ids) AND parent_entity_id = :parent_entity_id AND parent_entity_type = :parent_entity_type LIMIT :limit", TABLE_NAME );
	private final String SELECT_BY_IDS_PACKAGING_AND_COUNT = String.format( "SELECT * FROM %s WHERE id IN (:ids) AND is_packaging = :is_packaging LIMIT :limit", TABLE_NAME );
	private final String SELECT_BY_PARENT_TYPE_AND_PARENT_ID = String.format( "SELECT * FROM %s WHERE active = TRUE AND parent_entity_type = :parent_entity_type AND parent_entity_id = :parent_entity_id" , TABLE_NAME );

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

	// prepare query params
	private MapSqlParameterSource prepareInsertQueryParams( InventoryAccount inventoryAccount ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", inventoryAccount.getId() )
			.addValue( "title", inventoryAccount.getTitle() )
			.addValue( "parent_entity_type", inventoryAccount.getParentEntityType() )
			.addValue( "parent_entity_id", inventoryAccount.getParentEntityId() )
			.addValue( "active", inventoryAccount.getActive() )
			.addValue( "created_by", inventoryAccount.getCreatedBy() )
			.addValue( "created_at", inventoryAccount.getCreatedAt() )
			.addValue( "location_site_id", inventoryAccount.getLocationSiteId() )
			.addValue( "notes", inventoryAccount.getNotes() )
			.addValue("is_packaging", inventoryAccount.getIsPackaging() );
		return params;
	}

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

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

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

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

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

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

	public List<InventoryAccount> findByIdsAndProcessId( List<Long> accountIds, Long processId ){
		if( accountIds == null || accountIds.isEmpty() ){
			return new ArrayList<>();
		}
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "ids", accountIds );
		params.addValue( "parent_entity_id", processId );
		return namedParameterJdbcTemplate.query( SELECT_BY_IDS_AND_PARENT_ID, params, new InventoryAccountRowMapper() );
	}

	public List<InventoryAccount> findByIdsAndProcessIds( List<Long> accountIds, List<Long> processIds ){
		if( accountIds == null || accountIds.isEmpty() || processIds == null || processIds.isEmpty() ){
			return new ArrayList<>();
		}
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "ids", accountIds );
		params.addValue( "parent_entity_ids", processIds );
		return namedParameterJdbcTemplate.query( SELECT_BY_IDS_AND_PARENT_IDS, params, new InventoryAccountRowMapper() );
	}

	public List<InventoryAccount> findByIdsAndParentTypeAndIdAndLimit( List<Long> accountIds, Long count , String parentEntityType, String parentEntityId ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("ids" , accountIds );
		params.addValue("limit", count );
		params.addValue("parent_entity_type", parentEntityType );
		params.addValue("parent_entity_id", parentEntityId );
		return namedParameterJdbcTemplate.query( SELECT_BY_IDS_AND_PARENT_ENTITY_TYPE_AND_PARENT_ID_AND_COUNT, params, new InventoryAccountRowMapper() );
	}

	public List<InventoryAccount> findByIdsAndPackagingAndIdAndLimit( List<Long> accountIds, Long count, boolean isPackaging ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("ids" , accountIds );
		params.addValue("is_packaging", isPackaging );
		params.addValue("limit", count );
		return namedParameterJdbcTemplate.query( SELECT_BY_IDS_PACKAGING_AND_COUNT, params, new InventoryAccountRowMapper() );
	}

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

	public List<InventoryAccount> findByParentEntityTypeAndParentId( String parentEntityType, Long parentEntityId ){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("parent_entity_type" , parentEntityType );
		params.addValue("parent_entity_id", parentEntityId );
		return namedParameterJdbcTemplate.query( SELECT_BY_PARENT_TYPE_AND_PARENT_ID, params, new InventoryAccountRowMapper() );
	}
}