package ru.yandex.autotests.directapi.finance.createinvoice;

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.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.AxisError;
import ru.yandex.autotests.directapi.apiclient.errors.AxisErrorDetails;
import ru.yandex.autotests.directapi.finance.FinanceFeatures;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.finances.PayCampElementMap;
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.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;

/**
 * User: pavryabov
 * Date: 24.02.14
 */
@Aqua.Test
@Features(FinanceFeatures.CREATE_INVOICE)
public class CreateInvoiceByAgencyTest {
    protected LogSteps log = LogSteps.getLogger(this.getClass());

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

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

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

    private static String agencyLogin = Logins.AGENCY_RUB;
    private static String clientAgencyBase1 = Logins.SUBCLIENT_RUB;
    private static String clientAgencyBase2 = Logins.SUBCLIENT_RUB_2;

    private static long agClient1Camp1;
    private static long agClient1Camp2;
    private static long agClient2Camp1;
    private static long anotherClientCamp2;
    private static long clientCampElse;
    private static Money minInvoiceAmount = MoneyCurrency.get(Currency.RUB).getMinInvoiceAmount().addVAT();

    @BeforeClass
    public static void initTest() {
        api.as(agencyLogin);
        agClient1Camp1 = api.userSteps.campaignSteps().addDefaultTextCampaign(clientAgencyBase1);
        agClient1Camp2 = api.userSteps.campaignSteps().addDefaultTextCampaign(clientAgencyBase1);
        agClient2Camp1 = api.userSteps.campaignSteps().addDefaultTextCampaign(clientAgencyBase2);

        api.as(Logins.SUPER_LOGIN);
        anotherClientCamp2 = api.userSteps.campaignSteps().addDefaultTextCampaign(Logins.SPB_TESTER);

        api.as(Logins.AGENCY_ANOTHER);
        clientCampElse = api.userSteps.campaignSteps().addDefaultTextCampaign(Logins.CLIENT_AGENCY_ANOTHER);

        api.as(agencyLogin);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6179")
    public void testCreateInvoiceOneCampaign() {
        String requestID = api.userSteps.financeSteps().getRequestID(
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()));
        api.userSteps.balanceSteps().operator(User.get(agencyLogin)).requestAmountShouldBe(
                requestID, equalTo(minInvoiceAmount.floatValue()));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6180")
    public void testCreateInvoiceNoRightsCampaign() {
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(54, null),
                new PayCampElementMap(api.type())
                        .withCampaignID(clientCampElse)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue())
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6181")
    public void testCreateInvoiceOneCampaignTwoInvoice() {
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(354, AxisErrorDetails.PAYCAMPELEMENT_CAMPAIGNID_MUST_BE_UNIQUE),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue())
        );
    }

    //https://jira.yandex-team.ru/browse/DIRECT-24803
    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6182")
    public void testCreateInvoiceTwoCampaignOneNotMine() {
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(54, null),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()),
                new PayCampElementMap(api.type())
                        .withCampaignID(anotherClientCamp2)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue())
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6183")
    public void testCreateInvoiceTwoCampaignTwoInvoice() {
        String requestID = api.userSteps.financeSteps().getRequestID(
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp2)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()));
        api.userSteps.balanceSteps().operator(User.get(agencyLogin)).requestAmountShouldBe(
                requestID, equalTo(minInvoiceAmount.multiply(2).floatValue()));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6185")
    public void testCreateInvoiceTwoCampaignNoRight() {
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(54, null),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()),
                new PayCampElementMap(api.type())
                        .withCampaignID(clientCampElse)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue())
        );
        log.info("Вызовем метод, поменяв местами элементы кампаний для оплаты");
        api.userSteps.financeSteps().shouldGetErrorOnCreateInvoice(
                new AxisError(54, null),
                new PayCampElementMap(api.type())
                        .withCampaignID(clientCampElse)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue())
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("6186")
    public void testCreateInvoiceTwoAgClientsTwoInvoice() {
        String requestID = api.userSteps.financeSteps().getRequestID(
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient1Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()),
                new PayCampElementMap(api.type())
                        .withCampaignID(agClient2Camp1)
                        .withCurrency(Currency.RUB)
                        .withSum(minInvoiceAmount.floatValue()));
        api.userSteps.balanceSteps().operator(User.get(agencyLogin)).requestAmountShouldBe(
                requestID, equalTo(minInvoiceAmount.multiply(2f).floatValue()));
    }

//    @Test
//    public void testCreateInvoiceWithPaymentToken() {
//        int requestID;
//        String invoiceUrl = api.userSteps.financeSteps().createInvoiceWithPaymentToken(
//                new CreateInvoiceInfoMap(api.type()).withPayments(
//                        new PayCampElementMap(api.type())
//                                .withCampaignID(agClient1Camp1)
//                                .withSum(minInvoiceAmount.floatValue())
//                ));
//        try {
//            log.info("Квитанция сформирована: " + invoiceUrl);
//            String s = Parser.getMatchFromString(invoiceUrl, ".+(request_id%3D)(\\d{8}).+", 2);
//            requestID = Integer.parseInt(s);
//        } catch (Exception e) {
//            throw new DirectAPIException("Ошибка получения requestID из готовой ссылки на оплату", e);
//        }
//        api.userSteps.balanceSteps().operator(User.get(agencyLogin)).requestAmountShouldBe(
//                requestID, equalTo(minInvoiceAmount.convert(Currency.RUB).addVAT().floatValue()));
//    }ToDo broken payment token - DIRECT-41294
}
