package ru.yandex.autotests.direct.api.campaigns.update;

import java.util.Arrays;
import java.util.Collection;

import com.yandex.direct.api.v5.campaigns.AddResponse;
import com.yandex.direct.api.v5.campaigns.CpmBannerCampaignAddItem;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignAddItem;
import com.yandex.direct.api.v5.campaigns.TextCampaignAddItem;
import com.yandex.direct.api.v5.general.ArrayOfInteger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.api.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampMetrikaGoalsRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.enums.CampaignType;
import ru.yandex.autotests.directapi.model.api5.campaigns.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.campaigns.MetrikaGoals;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@Description("Обновление кампаний и создание целей с пустой статистикой")
@RunWith(Parameterized.class)
public class UpdateCampaignsSavingCampMetrikaGoalsTest {

    private static final String CLIENT = CampaignsLogins.CLIENT;
    private static final Integer COUNTER_ID = MetrikaGoals.getCounterForLogin(CLIENT);
    public static final long GOAL_ID = 13088934L;

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

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

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

    private DirectJooqDbSteps dbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT);


    @Parameterized.Parameter(0)
    public CampaignType type;

    private Long campaignId;

    @Parameterized.Parameters(name = "campaignType = {0}")
    public static Collection testData() {
        Object[][] data = new Object[][]{
                {CampaignType.TEXT,},
                {CampaignType.DYNAMIC},
                {CampaignType.CPM_BANNER}
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
    }

    @Before
    public void before() {
        CampaignAddItemMap campaignAddItemMap = getCampaignAddItemMap();

        AddResponse addResponse = api.userSteps.campaignSteps().shouldGetResultOnAdd(new AddRequestMap()
                .withCampaigns(campaignAddItemMap), ExpectedResult.success());

        campaignId = addResponse.getAddResults().stream().findAny().get().getId();
        dbSteps.campMetrikaGoalsSteps().deleteCampMetrikaGoals(campaignId, GOAL_ID);
    }

    @Test
    public void updateCampaignName_GoalsAreNotAdding() {
        CampaignUpdateItemMap campaignUpdateItemMap = new CampaignUpdateItemMap()
                .defaultCampaignUpdateItem()
                .withId(campaignId)
                .withName("updated name");

        api.userSteps.campaignSteps().campaignsUpdateWithCheck(campaignUpdateItemMap);
        CampMetrikaGoalsRecord campMetrikaGoalRecord =
                dbSteps.campMetrikaGoalsSteps().getCampMetrikaGoalRecord(campaignId, GOAL_ID);
        assertThat(campMetrikaGoalRecord, nullValue());
    }

    private CampaignAddItemMap getCampaignAddItemMap() {
        CampaignAddItemMap campaignAddItemMap = new CampaignAddItemMap()
                .defaultCampaignAddItem()
                .withDefaultCampaign(type);

        ArrayOfInteger counters = getCounters();

        switch (type) {
            case TEXT:
                ((TextCampaignAddItem) campaignAddItemMap.get("textCampaign")).setCounterIds(counters);
                break;
            case DYNAMIC:
                ((DynamicTextCampaignAddItem) campaignAddItemMap.get("dynamicTextCampaign")).setCounterIds(counters);
                break;
            case CPM_BANNER:
                ((CpmBannerCampaignAddItem) campaignAddItemMap.get("cpmBannerCampaign")).setCounterIds(counters);
        }
        return campaignAddItemMap;
    }

    private static ArrayOfInteger getCounters() {
        return getCounters(COUNTER_ID, 44041134, 57215176, 123);
    }

    private static ArrayOfInteger getCounters(Integer... counterIds) {
        ArrayOfInteger counters = new ArrayOfInteger();
        counters.setItems(Arrays.asList(counterIds));
        return counters;
    }

}
