package ru.yandex.autotests.direct.api.campaigns.add.negativekeywords;

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

import com.yandex.direct.api.v5.campaigns.AddResponse;
import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
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.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
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.CampaignGetItemMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directapi.steps.banners.KeywordPhraseGenerator;
import ru.yandex.autotests.directapi.steps.banners.KeywordsSteps;
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.Issue;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by pavryabov on 26.08.15.
 * https://st.yandex-team.ru/TESTIRT-6546
 */
@Aqua.Test
@Features(CampaignsFeatures.ADD)
@Description("Проверка сохранения несколько минус-слов")
@Issue("https://st.yandex-team.ru/DIRECT-34567")
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class NegativeKeywordsSeveralWordsTest {

    private static final String CLIENT = CampaignsLogins.CLIENT;

    @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);

    @Parameterized.Parameter(0)
    public String description;

    @Parameterized.Parameter(1)
    public String[] negativeKeywords;

    @Parameterized.Parameters(name = "{0}")
    public static Collection<Object[]> data() {
        KeywordPhraseGenerator keywordPhraseGenerator =
                new KeywordPhraseGenerator(KeywordsSteps.CYRILLIC_CHARS_NO_SPACE);

        return Arrays.asList(new Object[][]{
                {"Two negative keywords", new String[]{"кулеры", "кондиционеры"}},
                {"Two negative keywords with extra spaces", new String[]{" кулеры", "кондиционеры "}},
                {"Two keywords with maximum length",
                        keywordPhraseGenerator
                                .generatePhraseWithPlusAndMinusWords(
                                        new Integer[0],
                                        new Integer[]{KeywordsSteps.MINUS_WORD_MAX_LENGTH,
                                                KeywordsSteps.MINUS_WORD_MAX_LENGTH})
                                .minusWordArray()},
                {"Many keywords with total length at exactly the limit",
                        keywordPhraseGenerator
                                .generatePhraseWithPlusAndMinusWords(
                                        new Integer[0],
                                        KeywordPhraseGenerator
                                                .minusWordLengthsWithSpecificTotalLength(
                                                        KeywordsSteps.MINUS_WORD_MAX_LENGTH,
                                                        KeywordsSteps.MINUS_WORD_MAX_LENGTH,
                                                        CampaignAddItemMap.MAX_NEGATIVE_KEYWORDS_LENGTH
                                                )
                                                .toArray(new Integer[0]))
                                .minusWordArray()},
        });
    }

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

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("172")
    public void testNegativeKeywordsSeveralWords() {
        AddResponse addResponse = api.userSteps.campaignSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withCampaigns(new CampaignAddItemMap()
                                .defaultCampaignAddItem().withNegativeKeywords(negativeKeywords)
                                .withDefaultTextCampaign()
                        ),
                ExpectedResult.success());
        Long id = addResponse.getAddResults().get(0).getId();
        CampaignGetItem campaignGetItem =
                api.userSteps.campaignSteps().campaignsGet(id, CampaignFieldEnum.NEGATIVE_KEYWORDS);

        String[] negativeKeywordsBeforeSave = campaignGetItem.getNegativeKeywords().getValue().getItems().stream()
                .map(it -> it
                        .trim()
                        .replace('ё', 'е')
                        .replace('Ё', 'Е'))
                .sorted(String.CASE_INSENSITIVE_ORDER)
                .toArray(String[]::new);
        campaignGetItem = (CampaignGetItem) new CampaignGetItemMap()
                .withNegativeKeywords(negativeKeywordsBeforeSave).getBean();

        String[] negativeKeywordsAfterSave = Arrays.stream(negativeKeywords)
                .map(it -> it
                        .trim()
                        .replace('ё', 'е')
                        .replace('Ё', 'Е'))
                .sorted(String.CASE_INSENSITIVE_ORDER)
                .toArray(String[]::new);

        assertThat("поле NegativeKeywords сохранилось верно", campaignGetItem,
                beanDifferV5((CampaignGetItem)
                        new CampaignGetItemMap()
                                .withNegativeKeywords(negativeKeywordsAfterSave).getBean()));
    }
}
