package com.utopiaindustries.dao.ctp;


import com.utopiaindustries.model.ctp.User;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDAO {

    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private final String TABLE_NAME = "cut_to_pack.users";
    private final String SELECT_BY_USERNAME = String.format( "SELECT * FROM %s WHERE username = :username", TABLE_NAME );
    private final String FIND_ALL_QUERY = String.format( "SELECT * FROM %s", TABLE_NAME );
    private final String INSERT_QUERY = String.format( "INSERT INTO %s (username, password, enabled) VALUES (:username, :password, :enabled ) ON DUPLICATE KEY UPDATE username = :username, password = :password, enabled = :enabled", TABLE_NAME );

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

    // prepare query params
    private MapSqlParameterSource prepareInsertQueryParams(User user ) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "username", user.getUsername() )
                .addValue( "password", user.getPassword() )
                .addValue( "enabled", user.getEnabled() );
        return params;
    }

    public User findByUsername(String username ) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "username", username );
        return namedParameterJdbcTemplate.query( SELECT_BY_USERNAME, params, new UserRowMapper() )
                .stream()
                .findAny()
                .orElse( null );
    }

    public List<User> findAll() {
        return namedParameterJdbcTemplate.query( FIND_ALL_QUERY, new UserRowMapper() );
    }

    // save
    public int save( User user ){
        MapSqlParameterSource params = prepareInsertQueryParams( user );
        return namedParameterJdbcTemplate.update( INSERT_QUERY, params );
    }


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