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

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import org.apache.commons.lang3.RandomStringUtils;
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.ProtocolType;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
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.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
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 ginger on 22.08.15.
 * https://st.yandex-team.ru/TESTIRT-6809
 */
@Aqua.Test
@Issue("https://st.yandex-team.ru/DIRECT-34570")
@Features(CampaignsFeatures.UPDATE)
@Description("Проверка обновления поля NegativeKeywords")
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class UpdateNegativeKeywordsPositiveTest {

    private static String client = CampaignsLogins.UPDATE_CLIENT;

    @ClassRule
    public static ApiSteps api = new ApiSteps().version(104).as(client);

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

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

    private static Long campaignID;
    private CampaignGetItem campaignGetItem;

    @Parameterized.Parameter(0)
    public String description;

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

    @Parameterized.Parameter(2)
    public String[] negativeKeywordsAfterSave;

    @Parameterized.Parameter(3)
    public ProtocolType protocolType;

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

        String maxLengthNegativeKeyword =
                RandomStringUtils.randomAlphabetic(CampaignAddItemMap.MAX_NEGATIVE_KEYWORDS_LENGTH);

        KeywordPhraseGenerator.Result oneKeywordWithMaximumLength = keywordPhraseGenerator
                .generatePhraseWithPlusAndMinusWords(
                        new Integer[0],
                        new Integer[]{KeywordsSteps.MINUS_WORD_MAX_LENGTH});

        String[] negativeKeywordsBeforeSave = oneKeywordWithMaximumLength.minusWordArray();

        // Java заменяет ё на е
        String[] negativeKeywordsAfterSave = Stream.of(oneKeywordWithMaximumLength.minusWordArray())
                .map(it -> it
                        .trim()
                        .replace('ё', 'е')
                        .replace('Ё', 'Е'))
                .sorted(String.CASE_INSENSITIVE_ORDER)
                .toArray(String[]::new);

        return Arrays.asList(new Object[][]{
                {"One russian keyword", new String[]{"кулеры"}, new String[]{"кулеры"}, ProtocolType.JSON},
                {"One english keyword", new String[]{"english"}, new String[]{"english"}, ProtocolType.JSON},
                {"Two negative keywords",
                        new String[]{"кулеры", "кондиционеры"}, new String[]{"кондиционеры", "кулеры"},
                        ProtocolType.JSON},
                {"One keyword with maximum length",
                        negativeKeywordsBeforeSave, negativeKeywordsAfterSave, ProtocolType.JSON},
                {"+test", new String[]{"+test"}, new String[]{"+test"}, ProtocolType.JSON},
                {"!test", new String[]{"!test"}, new String[]{"!test"}, ProtocolType.JSON},
                {"te.st", new String[]{"te.st"}, new String[]{"te st"}, ProtocolType.JSON},
                {"test.", new String[]{"test."}, new String[]{"test"}, ProtocolType.JSON},
                {"1test", new String[]{"1test"}, new String[]{"1test"}, ProtocolType.JSON},
                {"te1st", new String[]{"te1st"}, new String[]{"te1st"}, ProtocolType.JSON},
                {"test1", new String[]{"test1"}, new String[]{"test1"}, ProtocolType.JSON},
                {" test", new String[]{" test"}, new String[]{"test"}, ProtocolType.JSON},
                {"test ", new String[]{"test "}, new String[]{"test"}, ProtocolType.JSON},
                // Поведение перла выглядит более правильно, разбираемся в https://st.yandex-team.ru/DIRECT-155695
                // {"арбуз, арбузов", new String[]{"арбуз", "арбузов"}, new String[]{"арбуз"}, ProtocolType.JSON},  // perl
                // {"арбуз, арбузов", new String[]{"арбуз", "арбузов"}, new String[]{"арбузов"}, ProtocolType.JSON},  // java
                {"null JSON", null, null, ProtocolType.JSON},
                {"null SOAP", null, null, ProtocolType.SOAP},
        });
    }

    @BeforeClass
    public static void createCampaign() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignID = api.userSteps.campaignSteps().addDefaultTextCampaign();
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("4822")
    public void updateNegativeKeywords() {
        //DIRECT-46411
        //DIRECT-47209
        api.protocol(protocolType);
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(campaignID)
                                .withNegativeKeywords(negativeKeywords)
                        ),
                ExpectedResult.success());
        campaignGetItem = api.userSteps.campaignSteps().campaignsGet(campaignID, CampaignFieldEnum.NEGATIVE_KEYWORDS);
        assertThat("кампания правильно обновилась", campaignGetItem,
                beanDifferV5((CampaignGetItem)
                        new CampaignGetItemMap()
                                .withNegativeKeywords(negativeKeywordsAfterSave).getBean()));
    }
}
