package ru.yandex.autotests.direct.api.bidmodifiers.delete;

import java.util.List;

import com.yandex.direct.api.v5.bidmodifiers.OperatingSystemTypeEnum;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.api.bidmodifiers.BidModifiersFeatures;
import ru.yandex.autotests.direct.api.bidmodifiers.BidModifiersLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.HierarchicalMultipliersRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.MobileMultiplierValuesRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifierAddMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.MobileAdjustmentMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Features(BidModifiersFeatures.DELETE)
@Tag(TagDictionary.TRUNK)
@Description("Проверка состояния БД при удаления мобильных корректировок c таргетингом на ОС")
public class DeleteMobileBidModifierAndCheckDbTest {
    private static final String CLIENT = BidModifiersLogins.SINGLE_CLIENT_DELETE;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(CLIENT);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    private static DirectJooqDbSteps jooqDbSteps;
    private static Long cpmCampaignId;

    @BeforeClass
    public static void createCampaign() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT);
        cpmCampaignId = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
    }

    @Before
    @Step("Подготовка данных для теста")
    public void prepareGroup() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);

    }

    @Test
    public void deleteIosAdjustmentAndCheckRecordInHierarchicalMultipliersTable() {
        AdGroupAndModifier adGroupAndModifier = createCmpGroupAndMobileBidModifierForIos(cpmCampaignId);

        api.userSteps.bidModifiersSteps().bidModifiersDelete(adGroupAndModifier.getBidModifierId());

        List<HierarchicalMultipliersRecord> hierarchicalMultipliersByPid =
                jooqDbSteps.multipliersSteps().getHierarchicalMultipliersByPid(adGroupAndModifier.getAdGroupId());
        assertThat("После удаления не осталось ни одной записи в hierarchical_multipliers",
                hierarchicalMultipliersByPid, empty());
    }

    @Test
    public void deleteIosAdjustmentAndCheckRecordInMobileMultiplierValuesTable() {
        AdGroupAndModifier adGroupAndModifier = createCmpGroupAndMobileBidModifierForIos(cpmCampaignId);

        api.userSteps.bidModifiersSteps().bidModifiersDelete(adGroupAndModifier.getBidModifierId());

        List<MobileMultiplierValuesRecord> mobileMultiplierValues = jooqDbSteps.multipliersSteps()
                .getMobileMultiplierValuesByAdGroupId(adGroupAndModifier.getAdGroupId());
        assertThat("После удаления не осталось ни одной записи в hierarchical_multipliers",
                mobileMultiplierValues, empty());
    }

    private AdGroupAndModifier createCmpGroupAndMobileBidModifierForIos(Long cpmCampaignId) {
        Long adGroupId = api.userSteps.adGroupsSteps().addDefaultCpmBannerKeywordsAdGroup(cpmCampaignId);
        List<Long> ids = api.userSteps.bidModifiersSteps().bidModifiersAdd(
                new BidModifierAddMap()
                        .withAdGroupId(adGroupId)
                        .withMobileAdjustment(new MobileAdjustmentMap()
                                .withOperatingSystemType(OperatingSystemTypeEnum.IOS)
                                .withBidModifier(BidModifierAddMap.DEFAULT_BID_MODIFIER))
        );
        assumeThat("Создана одна корректировка", ids, contains(notNullValue()));
        return new AdGroupAndModifier(adGroupId, ids.get(0));
    }

    private class AdGroupAndModifier {
        private final Long adGroupId;
        private final Long bidModifierId;

        private AdGroupAndModifier(Long adGroupId, Long bidModifierId) {
            this.adGroupId = adGroupId;
            this.bidModifierId = bidModifierId;
        }

        public Long getAdGroupId() {
            return adGroupId;
        }

        public Long getBidModifierId() {
            return bidModifierId;
        }
    }
}
