package ru.yandex.qe.dispenser.domain.dao.bot.provider.group;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.google.common.collect.ImmutableMap;
import org.postgresql.util.PGobject;

import ru.yandex.qe.dispenser.domain.ProviderGroup;
import ru.yandex.qe.dispenser.domain.dao.SqlDaoBase;
import ru.yandex.qe.dispenser.domain.dao.SqlUtils;

public class SqlProviderGroupDao extends SqlDaoBase implements ProviderGroupDao {
    private static final String INSERT_QUERY = "INSERT INTO provider_group (name, description, priority, campaign_id, settings) VALUES (:name, :description, :priority, :campaignId, :settings)";

    private static final String GET_BY_CAMPAIGN_ID = "SELECT * FROM provider_group pg WHERE pg.campaign_id IN (:campaignId) ORDER BY priority";

    private static final String CLEAR_QUERY = "TRUNCATE provider_group CASCADE";


    @Override
    public List<ProviderGroup> getProviderGroupsByCampaignId(final long campaignId) {
        return jdbcTemplate.query(GET_BY_CAMPAIGN_ID, Collections.singletonMap("campaignId", campaignId), this::toProviderGroup);
    }

    @Override
    public ProviderGroup create(final ProviderGroup providerGroup) {
        final long id = jdbcTemplate.insert(INSERT_QUERY, toParams(providerGroup));
        providerGroup.setId(id);
        return providerGroup;
    }

    @Override
    public boolean clear() {
        return jdbcTemplate.update(CLEAR_QUERY) > 0;
    }

    private Map<String, Object> toParams(final ProviderGroup providerGroup) {
        return ImmutableMap.<String, Object>builder()
                .put("name", providerGroup.getName())
                .put("description", providerGroup.getDescription())
                .put("priority", providerGroup.getPriority())
                .put("campaignId", providerGroup.getCampaignId())
                .put("settings", SqlUtils.toJsonb(providerGroup.getSettings()))
                .build();
    }


    private ProviderGroup toProviderGroup(final ResultSet rs, final int ignored) throws SQLException {

        final ProviderGroup providerGroup = new ProviderGroup(
                rs.getString("name"),
                rs.getString("description"),
                rs.getLong("campaign_id"),
                rs.getInt("priority"),
                SqlUtils.fromJsonb((PGobject) rs.getObject("settings"), ProviderGroup.ProviderGroupSettings.class)
        );

        providerGroup.setId(rs.getLong("id"));

        return providerGroup;
    }


}
