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

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

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.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.User;
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.ResumeRequestMap;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.SuspendRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.IdsCriteriaMap;
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.autotests.irt.testutils.beandiffer2.beanfield.BeanFieldPath;
import ru.yandex.autotests.irt.testutils.beandiffer2.comparestrategy.defaultcomparestrategy.DefaultCompareStrategies;
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.iterableWithSize;
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 buhter on 03/03/16
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(AudienceTargetsFeatures.RESUME)
@Description("Проверка работы метода в базе")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
public class ResumeAudienceTargetsAndCheckDBTest {
    private static final String LOGIN = AudienceTargetsLogins.LOGIN_TARGET35;

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

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

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

    private static Long audienceTargetId;
    private static int shard;
    private static String lastChange;
    private static Timestamp modtime;
    private static BidsRetargetingRecord actualBidsRetargeting;
    private static BidsRetargetingRecord bidsRetargetingAfterResume;
    private static GroupFakeInfo actualGroupFakeInfo;

    @BeforeClass
    public static void init() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
    }

    @BeforeClass
    public static void prepare() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        Long goalId =
                api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL).get(0);
        Long retargetingListsId = api.userSteps.retargetingListsSteps().addDefaultRetargetingLists(goalId);

        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        List<Long> audienceTargetIds = api.userSteps.audienceTargetsSteps().add(new AddRequestMap()
                .withAudienceTargets(new AudienceTargetAddItemMap()
                        .withAdGroupId(pid)
                        .withRetargetingListId(retargetingListsId)
                        .withContextBid(MoneyCurrency.get(User.get(LOGIN).getCurrency()).getLongMinPrice().longValue()))
        );
        assumeThat("создался один объект", audienceTargetIds, iterableWithSize(1));
        audienceTargetId = audienceTargetIds.get(0);

        api.userSteps.audienceTargetsSteps().shouldGetResultOnSuspend(
                new SuspendRequestMap()
                        .withSelectionCriteria(
                                new IdsCriteriaMap()
                                        .withIds(audienceTargetIds.get(0))),
                ExpectedResult.success()
        );

        lastChange = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(LocalDateTime.now().minusMinutes(5));
        GroupFakeInfo groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(pid);
        groupFakeInfo.setLastChange(lastChange);
        groupFakeInfo.setStatusBsSynced(Status.YES);
        groupFakeInfo.setStatusModerate(Status.YES);
        groupFakeInfo.setStatusPostModerate(Status.YES);
        api.userSteps.groupFakeSteps().updateGroupParams(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(audienceTargetId)
                .setModtime(modtime)
                .setIsSuspended(1);
        api.userSteps.getDirectJooqDbSteps().bidsRetargetingSteps().updateBidsRetargeting(bidsRetargeting);
        actualBidsRetargeting = api.userSteps.getDirectJooqDbSteps().bidsRetargetingSteps()
                .getBidsRetargeting(audienceTargetId);
        assumeThat("ретаргетингу установились ожидаемые параметры", actualBidsRetargeting, recordDiffer(bidsRetargeting));

        api.userSteps.audienceTargetsSteps().shouldGetResultOnResume(
                new ResumeRequestMap()
                        .withSelectionCriteria(
                                new IdsCriteriaMap()
                                        .withIds(audienceTargetIds.get(0))),
                ExpectedResult.success()
        );

        actualGroupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(pid);
        bidsRetargetingAfterResume = api.userSteps.getDirectJooqDbSteps().bidsRetargetingSteps()
                .getBidsRetargeting(audienceTargetId);
    }

    @Test
    public void checkBidsRetargetingExceptModtime() {
        actualBidsRetargeting.setIsSuspended(0);
        assertThat("вызов метода suspend правильно изменил запись в базе"
                , bidsRetargetingAfterResume, recordDiffer(actualBidsRetargeting)
                        .useCompareStrategy(DefaultCompareStrategies.allFieldsExcept(BeanFieldPath.newPath("modtime")))
        );
    }

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

    @Test
    public void checkAdGroupStatusBsSynced() {
        //DIRECT-58299
        assertThat("группа не синхронизирована с БК", actualGroupFakeInfo.getStatusBsSynced(), equalTo(Status.NO));
    }

    @Test
    public void checkAdGroupLastChange() {
        assertThat("у группы обновился LastChange", actualGroupFakeInfo.getLastChange(), not(equalTo(lastChange)));
    }
}
