package ru.yandex.autotests.direct.api.audiencetargets.setbids;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

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.audiencetargets.AudienceTargetsFeatures;
import ru.yandex.autotests.direct.api.audiencetargets.AudienceTargetsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BidsRetargetingRecord;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.fake.GroupFakeInfo;
import ru.yandex.autotests.directapi.darkside.model.Status;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.AudienceTargetAddItemMap;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.AudienceTargetSetBidsItemMap;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.SetBidsRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.general.SetBidsExpectedResult;
import ru.yandex.autotests.directapi.model.retargeting.RetargetingGoalType;
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.allure.annotations.Issue;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static ru.yandex.autotests.direct.db.utils.JooqRecordDifferMatcher.recordDiffer;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

/**
 * Created by pavryabov on 10.09.16.
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(AudienceTargetsFeatures.SET_BIDS)
@Description("Проверка изменения статусов группы и ретаргетинга после изменения ставки")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
public class ChangeContextBidAndCheckStatusesTest {

    private static final String LOGIN = AudienceTargetsLogins.LOGIN_TARGET54;
    private static Long targetId;
    private static Long pid;
    private static String lastChange;
    private static Timestamp modtime;
    private static int shard;
    private static GroupFakeInfo groupFakeInfo;
    private static BidsRetargetingRecord actualBidsRetargeting;

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

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

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

    @BeforeClass
    public static void addUnitsToClient() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaignWithStrategies(
                new TextCampaignSearchStrategyAddMap().defaultServingOff(),
                new TextCampaignNetworkStrategyAddMap().defaultMaximumCoverage()
        );
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long goalId = api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL).get(0);
        Long retargetingListsId = api.userSteps.retargetingListsSteps().addDefaultRetargetingLists(goalId);
        Long contextBid = MoneyCurrency.get(Currency.RUB).getMinPrice().bidLong().longValue();
        targetId = api.userSteps.audienceTargetsSteps().add(
                new AddRequestMap()
                        .withAudienceTargets(
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(pid)
                                        .withRetargetingListId(retargetingListsId)
                                        .withContextBid(contextBid)
                        )).get(0);

        lastChange = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(LocalDateTime.now().minusMinutes(5));
        groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(pid);
        groupFakeInfo.setLastChange(lastChange);
        groupFakeInfo.setStatusBsSynced(Status.YES);
        api.userSteps.groupFakeSteps().updateGroupParams(groupFakeInfo);
        GroupFakeInfo actualGroupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(pid);
        assumeThat("группе установились ожидаемые параметры", actualGroupFakeInfo, beanDiffer(groupFakeInfo));

        modtime = Timestamp.valueOf(LocalDateTime.now().minusMinutes(5).withNano(0));
        BidsRetargetingRecord bidsRetargeting = api.userSteps.getDirectJooqDbSteps().useShard(shard).bidsRetargetingSteps()
                .getBidsRetargeting(targetId)
                .setModtime(modtime);

        api.userSteps.getDirectJooqDbSteps().bidsRetargetingSteps().updateBidsRetargeting(bidsRetargeting);
        actualBidsRetargeting = api.userSteps.getDirectJooqDbSteps().bidsRetargetingSteps()
                .getBidsRetargeting(targetId);
        assumeThat("ретаргетингу установились ожидаемые параметры", actualBidsRetargeting, recordDiffer(bidsRetargeting));

        api.userSteps.audienceTargetsSteps().shouldGetResultOnSetBids(new SetBidsRequestMap()
                        .withBids(new AudienceTargetSetBidsItemMap()
                                .withId(targetId)
                                .withContextBid(contextBid + 10000)),
                SetBidsExpectedResult.successWithId());

        actualBidsRetargeting = api.userSteps.getDirectJooqDbSteps().bidsRetargetingSteps()
                .getBidsRetargeting(targetId);
    }

    @Test
    public void checkAdGroups() {
        GroupFakeInfo actualGroupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(pid);
        assumeThat("параметры группы не обновились", actualGroupFakeInfo, beanDiffer(groupFakeInfo));
    }

    @Test
    public void checkBidsRetargetingModtime() {
        assertThat("у ретаргетинга обновился modtime", actualBidsRetargeting.getModtime(), not(equalTo(modtime)));
    }
}
