package ru.yandex.autotests.directapi.agencyclients.get;

import com.yandex.direct.api.v5.agencyclients.AgencyClientFieldEnum;
import com.yandex.direct.api.v5.agencyclients.GetResponse;
import com.yandex.direct.api.v5.general.YesNoEnum;
import com.yandex.direct.api.v5.generalclients.ClientSettingGetEnum;
import org.hamcrest.collection.IsCollectionWithSize;
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.db.models.jooq.ppc.enums.ClientsAllowCreateScampBySubclient;
import ru.yandex.autotests.directapi.agencyclients.AgencyClientsFeatures;
import ru.yandex.autotests.directapi.agencyclients.AgencyClientsLogins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.matchers.beans.BeanAssert;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.api5.agencyclients.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.generalclients.ClientSettingGetItemMap;
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.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.IsNot.not;
import static ru.yandex.autotests.directapi.matchers.beans.AnyItem.anyItem;
import static ru.yandex.autotests.directapi.matchers.beans.EveryItem.everyItem;
import static ru.yandex.autotests.directapi.matchers.beans.FieldMatcher.hasField;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Features(AgencyClientsFeatures.GET)
@Description("Проверка получения Settings.SharedAccountEnabled для различных вариантах подключенных ОС")
public class GetSettingsSharedAccountEnabledTest {
    private static final String AGENCY_CHIEF_LOGIN = AgencyClientsLogins.AGENCY_RUB;
    private static final String AGENCY_REP_WITH_PERMS_LOGIN = AgencyClientsLogins.AGENCY_RUB_REP1;
    private static final String AGENCY_REP_WITHOUT_PERMS_LOGIN = AgencyClientsLogins.AGENCY_RUB_REP2;
    private static final String SUBCLIENT_LOGIN_WITH_ACCOUNT = AgencyClientsLogins.AGENCY_RUB_SUBCLIENT;
    private static final String SUBCLIENT_LOGIN_WITHOUT_ACCOUNT = AgencyClientsLogins.AGENCY_RUB_SUBCLIENT1;
    private static final String SUBCLIENT_WITH_FREEDOM_LOGIN = AgencyClientsLogins.AGENCY_RUB_SUBCLIENT2_WITH_FREEDOM;

    @ClassRule
    public static ApiSteps api = new ApiSteps();

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

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

    @BeforeClass
    @Step("Подготовка и проверка тестовых данных перед всеми тестами")
    public static void commonPrepare() {
        // [SUBCLIENT_LOGIN_WITH_ACCOUNT] включаем агентский общий счёт
        api.as(AGENCY_CHIEF_LOGIN);
        api.userSteps.financeSteps().verifySharedAccount(SUBCLIENT_LOGIN_WITH_ACCOUNT);
        assumeThat("агентский общий счёт подключен",
                api.userSteps.financeSteps().getAccount(SUBCLIENT_LOGIN_WITH_ACCOUNT), notNullValue());

        // [SUBCLIENT_LOGIN_WITHOUT_ACCOUNT] проверяем что нет агентского общего счёта
        api.as(AGENCY_CHIEF_LOGIN);
        assumeThat("агентский общий счёт не подключен",
                api.userSteps.financeSteps().getAccount(SUBCLIENT_LOGIN_WITHOUT_ACCOUNT), nullValue());

        // [SUBCLIENT_WITH_FREEDOM_LOGIN] проверяем что нет агентского общего счёта
        api.as(AGENCY_CHIEF_LOGIN);
        assumeThat("агентский общий счёт не подключен",
                api.userSteps.financeSteps().getAccount(SUBCLIENT_WITH_FREEDOM_LOGIN), nullValue());

        // [SUBCLIENT_WITH_FREEDOM_LOGIN] включаем клиентский общий счёт
        api.as(Logins.SUPER_LOGIN);
        Long clientId = Long.valueOf(User.get(SUBCLIENT_WITH_FREEDOM_LOGIN).getClientID());
        api.userSteps.getDirectJooqDbSteps().useShardForLogin(SUBCLIENT_WITH_FREEDOM_LOGIN)
                .clientsSteps().setFree(clientId, ClientsAllowCreateScampBySubclient.Yes);
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(SUBCLIENT_WITH_FREEDOM_LOGIN);
        api.userSteps.createAccountForFreeClient(SUBCLIENT_WITH_FREEDOM_LOGIN);
        api.as(SUBCLIENT_WITH_FREEDOM_LOGIN);
        assumeThat("клиентский общий счёт подключен",
                api.userSteps.financeSteps().getAccount(SUBCLIENT_WITH_FREEDOM_LOGIN), notNullValue());
    }

    @Before
    @Step("Подготовка тестовых данных перед каждым тестом")
    public void prepare() {
        api.as(AGENCY_CHIEF_LOGIN);
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AGENCY_CHIEF_LOGIN);
    }

    @Test
    public void getSharedAccountEnabledForSubclientWithAccountTest() {
        GetResponse response = api.userSteps.agencyClientsStepsV5().agencyClientsGet(
                new GetRequestMap().withSubclientLogins(SUBCLIENT_LOGIN_WITH_ACCOUNT)
                        .withFieldNames(AgencyClientFieldEnum.SETTINGS));

        assumeThat("полученный список с данными 1 клиента", response.getClients(), IsCollectionWithSize.hasSize(1));

        BeanAssert.with(response.getClients().get(0).getSettings().toArray()).assertThat(anyItem(allOf(
                hasField(ClientSettingGetItemMap.OPTION, equalTo(ClientSettingGetEnum.SHARED_ACCOUNT_ENABLED)),
                hasField(ClientSettingGetItemMap.VALUE, equalTo(YesNoEnum.YES)))));
    }

    @Test
    public void getSharedAccountEnabledForSubclientWithAccountByRepWithPermsTest() {
        GetResponse response = api.as(AGENCY_REP_WITH_PERMS_LOGIN).userSteps.agencyClientsStepsV5().agencyClientsGet(
                new GetRequestMap().withSubclientLogins(SUBCLIENT_LOGIN_WITH_ACCOUNT)
                        .withFieldNames(AgencyClientFieldEnum.SETTINGS));

        assumeThat("полученный список с данными 1 клиента", response.getClients(), IsCollectionWithSize.hasSize(1));

        BeanAssert.with(response.getClients().get(0).getSettings().toArray()).assertThat(anyItem(allOf(
                hasField(ClientSettingGetItemMap.OPTION, equalTo(ClientSettingGetEnum.SHARED_ACCOUNT_ENABLED)),
                hasField(ClientSettingGetItemMap.VALUE, equalTo(YesNoEnum.YES)))));
    }

    @Test
    public void getSharedAccountEnabledForSubclientWithAccountByRepWithoutPermsTest() {
        GetResponse response = api.as(AGENCY_REP_WITHOUT_PERMS_LOGIN).userSteps.agencyClientsStepsV5().agencyClientsGet(
                new GetRequestMap().withSubclientLogins(SUBCLIENT_LOGIN_WITH_ACCOUNT)
                        .withFieldNames(AgencyClientFieldEnum.SETTINGS));

        BeanAssert.with(response.getClients()).assertThat(hasSize(0));
    }

    @Test
    public void getSharedAccountEnabledForSubclientWithoutAccountTest() {
        GetResponse response = api.userSteps.agencyClientsStepsV5().agencyClientsGet(
                new GetRequestMap().withSubclientLogins(SUBCLIENT_LOGIN_WITHOUT_ACCOUNT)
                        .withFieldNames(AgencyClientFieldEnum.SETTINGS));

        assumeThat("полученный список с данными 1 клиента", response.getClients(), IsCollectionWithSize.hasSize(1));

        BeanAssert.with(response.getClients().get(0).getSettings().toArray()).assertThat(everyItem(not(allOf(
                hasField(ClientSettingGetItemMap.OPTION, equalTo(ClientSettingGetEnum.SHARED_ACCOUNT_ENABLED)),
                hasField(ClientSettingGetItemMap.VALUE, equalTo(YesNoEnum.YES))))));
    }
}
