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

import java.util.List;

import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
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.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.common.api45.CreateNewSubclientResponse;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.Action;
import ru.yandex.autotests.directapi.model.api5.campaigns.DeleteRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.IdsCriteriaMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
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.emptyIterable;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by chicos on 24.08.15.
 */
@Aqua.Test
@Features(CampaignsFeatures.DELETE)
@Description("Проверка удаления кампаний при включенном ОС")
@Tag(TagDictionary.TRUNK)
public class DeleteCampaignsFromAccountTest {
    private LogSteps log = LogSteps.getLogger(this.getClass());
    private static final String agencyLogin = Logins.AGENCY_LOGIN_ACCOUNT_ENABLED;

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

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

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

    private static Long campaignID1;
    private static Long campaignID2;
    private static String subClient;
    private static Integer accountID;
    private static final Currency currency = Currency.RUB;
    private static final Money sumToAdd = MoneyCurrency.get(currency).getMinInvoiceAmount();

    @BeforeClass
    public static void prepareCampaigns() {
        api.userSteps.clientFakeSteps().enableToCreateSubClients(agencyLogin);
        api.userSteps.clientFakeSteps().enableAgencyWallet(agencyLogin);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void createSubclientWithAccount() {
        //DIRECT-45412
        log.info("Создадим субклиента");
        CreateNewSubclientResponse createNewSubclientResponse =
                api.userSteps.clientSteps().createNewAgencySubClient("subClient", agencyLogin, currency);
        subClient = createNewSubclientResponse.getLogin();
        log.info("Создадим субклиенту две кампании и включим ОС");
        campaignID1 = api.userSteps.campaignSteps().addDefaultTextCampaign(subClient);
        campaignID2 = api.userSteps.campaignSteps().addDefaultTextCampaign(subClient);
        accountID = api.userSteps.financeSteps().enableAndGetSharedAccount(subClient);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("337")
    public void deleteLastCampaignAfterCreateInvoice() {
        log.info("Выставляем счет на этот кошелек. Не оплачиваем");
        api.userSteps.financeSteps().invoice(accountID, sumToAdd.addVAT().floatValue(), currency);
        log.info("Удаляем первую кампанию");
        api.userSteps.campaignSteps().campaignsDelete(subClient, campaignID1);
        log.info("Удаляем вторую кампанию");
        api.userSteps.campaignSteps().shouldGetResultOn(
                subClient,
                Action.DELETE,
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID2)),
                ExpectedResult.success(campaignID2)
        );

        List<CampaignGetItem> campaigns =
                api.userSteps.campaignSteps().getCampaigns(subClient, campaignID1, campaignID2);
        assertThat("кампании успешно удалены", campaigns, emptyIterable());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("336")
    public void deleteLastCampaignFromAccountWithMoneyTest() {
        log.info("Оплачиваем фейково кошелек");
        api.userSteps.campaignFakeSteps().sendFakeNotificationFromBalance(
                accountID,
                sumToAdd.addVAT().floatValue(),
                currency);
        log.info("Удаляем первую кампанию");
        api.userSteps.campaignSteps().campaignsDelete(subClient, campaignID1);
        log.info("Удаляем вторую кампанию");
        api.userSteps.campaignSteps().shouldGetResultOn(
                subClient,
                Action.DELETE,
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID2)),
                ExpectedResult.success(campaignID2)
        );

        List<CampaignGetItem> campaigns =
                api.userSteps.campaignSteps().getCampaigns(subClient, campaignID1, campaignID2);
        assertThat("кампании успешно удалены", campaigns, emptyIterable());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("335")
    public void deleteLastCampaignNoInvoicesOnAccountTest() {
        log.info("Удаляем первую кампанию");
        api.userSteps.campaignSteps().campaignsDelete(subClient, campaignID1);
        log.info("Удаляем вторую кампанию");
        api.userSteps.campaignSteps().shouldGetResultOn(
                subClient,
                Action.DELETE,
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID2)),
                ExpectedResult.success(campaignID2)
        );

        List<CampaignGetItem> campaigns =
                api.userSteps.campaignSteps().getCampaigns(subClient, campaignID1, campaignID2);
        assertThat("кампании успешно удалены", campaigns, emptyIterable());
    }
}
