package ru.yandex.autotests.direct.api.campaigns.update.textcampaign.strategy;

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

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import com.yandex.direct.api.v5.campaigns.TextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignNetworkStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignStrategy;
import org.junit.Before;
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.money.Currency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageRoiMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyNetworkDefaultMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.campaigns.MetrikaGoals;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
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.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by chicos on 04.09.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Позитивные сценарии создания текстовой кампании с автостратегиями для Search и комбинациями стратегий " +
        "для Network")
@Tag(TagDictionary.TRUNK)
public class StrategyCombinationsAutoSearchTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long goalId = MetrikaGoals.getGoalForCounter(counterId);
    private Long campaignId;

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

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

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

    @Parameterized.Parameter(value = 0)
    public String searchName;

    @Parameterized.Parameter(value = 1)
    public String contextName;

    @Parameterized.Parameter(value = 2)
    public TextCampaignSearchStrategyMap searchStrategy;

    @Parameterized.Parameter(value = 3)
    public TextCampaignNetworkStrategyMap networkStrategy;

    @Parameterized.Parameter(value = 4)
    public TextCampaignSearchStrategyMap expectedSearchStrategy;

    @Parameterized.Parameter(value = 5)
    public TextCampaignNetworkStrategyMap expectedNetworkStrategy;

    @Parameterized.Parameters(name = "search = {0}, context = {1}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                //DIRECT-45818
                //ServingOff для Network
                {"AverageCpc", "ServingOff",
                        new TextCampaignSearchStrategyMap().defaultAverageCpc(currency),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                        new TextCampaignSearchStrategyMap().defaultAverageCpc(currency),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                },
                {"AverageCpa", "ServingOff",
                        new TextCampaignSearchStrategyMap().defaultAverageCpa(currency, goalId),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                        new TextCampaignSearchStrategyMap().defaultAverageCpa(currency, goalId),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                },
                {"MaximumConversionRate", "ServingOff",
                        new TextCampaignSearchStrategyMap().defaultWbMaximumConversionRate(currency, goalId),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                        new TextCampaignSearchStrategyMap().defaultWbMaximumConversionRate(currency, goalId),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                },
                {"MaximumClicks", "ServingOff",
                        new TextCampaignSearchStrategyMap().defaultWbMaximumClicks(currency),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                        new TextCampaignSearchStrategyMap().defaultWbMaximumClicks(currency),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                },
                {"AverageRoi", "ServingOff",
                        new TextCampaignSearchStrategyMap().defaultAverageRoi(goalId),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                        new TextCampaignSearchStrategyMap()
                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_ROI)
                                .withAverageRoi(new StrategyAverageRoiMap()
                                .defaultStrategyAverageRoi()
                                .withGoalId(goalId)
                                .withProfitability(null)
                                .withWeeklySpendLimit(null)
                                .withBidCeiling(null)),
                        new TextCampaignNetworkStrategyMap().defaultServingOff(),
                },

                //NetworkDefault для Network
                {"AverageCpc", "NetworkDefault",
                        new TextCampaignSearchStrategyMap().defaultAverageCpc(currency),
                        new TextCampaignNetworkStrategyMap().defaultNetworkDefault(),
                        new TextCampaignSearchStrategyMap().defaultAverageCpc(currency),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ),
                },
                {"AverageCpa", "NetworkDefault",
                        new TextCampaignSearchStrategyMap().defaultAverageCpa(currency, goalId),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ).withNetworkDefault(new StrategyNetworkDefaultMap()),
                        new TextCampaignSearchStrategyMap().defaultAverageCpa(currency, goalId),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ),
                },
                {"MaximumConversionRate", "NetworkDefault",
                        new TextCampaignSearchStrategyMap().defaultWbMaximumConversionRate(currency, goalId),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ).withNetworkDefault(new StrategyNetworkDefaultMap()),
                        new TextCampaignSearchStrategyMap().defaultWbMaximumConversionRate(currency, goalId),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ),
                },
                {"MaximumClicks", "NetworkDefault",
                        new TextCampaignSearchStrategyMap().defaultWbMaximumClicks(currency),
                        new TextCampaignNetworkStrategyMap().defaultNetworkDefault(),
                        new TextCampaignSearchStrategyMap().defaultWbMaximumClicks(currency),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ),
                },
                {"AverageRoi", "NetworkDefault",
                        new TextCampaignSearchStrategyMap().defaultAverageRoi(goalId),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ).withNetworkDefault(new StrategyNetworkDefaultMap()),
                        new TextCampaignSearchStrategyMap()
                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_ROI)
                                .withAverageRoi(new StrategyAverageRoiMap()
                                .defaultStrategyAverageRoi()
                                .withGoalId(goalId)
                                .withProfitability(null)
                                .withWeeklySpendLimit(null)
                                .withBidCeiling(null)),
                        new TextCampaignNetworkStrategyMap().withBiddingStrategyType(
                                TextCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT
                        ),
                }
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1123")
    public void strategyNetworkTest() {
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                .addCampMetrikaGoals(campaignId, goalId, 100L, 100L);

        api.userSteps.campaignSteps().campaignsUpdateWithCheck(new CampaignUpdateItemMap()
                .withId(campaignId)
                .withTextCampaign(new TextCampaignUpdateItemMap()
                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                .withSearch(searchStrategy)
                                .withNetwork(networkStrategy))));

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(campaignId))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withTextCampaignFieldNames(TextCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));
        TextCampaignStrategy actualStrategy = campaigns.get(0).getTextCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

        TextCampaignStrategyMap expectedStrategy = new TextCampaignStrategyMap()
                .withSearch(expectedSearchStrategy)
                .withNetwork(expectedNetworkStrategy);

        assertThat("получили корректные стратегии", actualStrategy,
                beanDifferV5((TextCampaignStrategy) expectedStrategy.getBean()));
    }
}
