package com.utopiaindustries.dao.ctp;

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

	private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	private final String TABLE_NAME = "cut_to_pack.process";
	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 ASC", 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, notes) VALUES (:id, :title, :notes) ON DUPLICATE KEY UPDATE title = VALUES(title), notes = VALUES(notes)", TABLE_NAME );

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

	// prepare query params
	private MapSqlParameterSource prepareInsertQueryParams( Process process ) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue( "id", process.getId() )
			.addValue( "title", process.getTitle() )
			.addValue( "notes", process.getNotes() );
		return params;
	}

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

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

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

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

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