package ru.yandex.autotests.direct.handles.service;

import java.util.Date;
import java.util.HashMap;

import org.springframework.stereotype.Service;

import ru.yandex.autotests.balance.lib.environment.Environment;
import ru.yandex.autotests.balance.lib.integration.TestBalanceUtils;
import ru.yandex.autotests.balance.lib.xmlrpc.UnitTestLib;
import ru.yandex.autotests.direct.handles.beans.BalanceClientBean;
import ru.yandex.autotests.directapi.exceptions.DirectAPIException;
import ru.yandex.autotests.directapi.exceptions.UserNotFoundException;
import ru.yandex.autotests.directapi.model.User;

/**
 * Author buhter
 * Date 07.05.14
 */
@Service
public class BalanceClientService {

    private static final int SERVICE_ID = 7;
    private static final int FIRM_ID = 1;

    public BalanceClientBean updateClient(BalanceClientBean balanceClientBean) {
        if (balanceClientBean.getCurrency().equals("null")) {
            balanceClientBean.setCurrency(null);
        }
        try {
            new UnitTestLib(Environment.valueOf(balanceClientBean.getBalanceStage()))
                    .createClient(
                            balanceClientBean.getClientId(),
                            null,
                            null,
                            balanceClientBean.getCountry(),
                            balanceClientBean.getCurrency(), new Date(1), SERVICE_ID);
            return getClientInfo(balanceClientBean);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public BalanceClientBean getClientInfo(BalanceClientBean balanceClientBean) {
        Environment environment = Environment.valueOf(balanceClientBean.getBalanceStage());
        UnitTestLib unitTestLib = new UnitTestLib(environment);

        Object client;
        try {
            client = unitTestLib.findClientById(balanceClientBean.getClientId());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }


        if (client != null) {
            Object[] clientInfo = (Object[]) ((Object[]) client)[2];
            if (clientInfo.length != 0) {
                HashMap<String, Object> clientInfoMap = (HashMap<String, Object>) clientInfo[0];
                try {
                    balanceClientBean.setCountry((Integer) clientInfoMap.get("REGION_ID"));
                    balanceClientBean.setIsAgency((Integer) clientInfoMap.get("IS_AGENCY"));
                } catch (ClassCastException e) {
                    balanceClientBean.setCountry(0);
                }
                HashMap<String, Object> serviceData = (HashMap<String, Object>) clientInfoMap.get("SERVICE_DATA");
                try {
                    HashMap<String, String> directData = (HashMap<String, String>) serviceData.get("7");
                    balanceClientBean.setCurrency(directData.get("CURRENCY"));
                } catch (NullPointerException e) {
                    balanceClientBean.setCurrency("NOT SET OR YNDX_FIXED");
                }
                return balanceClientBean;
            } else {
                throw new IllegalStateException(
                        "Не удалось получить информацию о клиенте соответствующем переданным параметрам.");
            }
        }
        throw new IllegalStateException(
                "Не найдено ни одного клиента соответствующего переданным параметрам.");
    }

    public void turnOnInvoice(int invoiceId, String balanceStage) {
        try {
            UnitTestLib unitTestLib = new UnitTestLib(Environment.valueOf(balanceStage));
            unitTestLib.turnOnInvoice(invoiceId);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public void doCampaings(String orderId, double qty, String balanceStage) {
        try {
            UnitTestLib unitTestLib = new UnitTestLib(Environment.valueOf(balanceStage));
            unitTestLib.doCampaigns(SERVICE_ID, orderId, qty);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public String getClientOverdraft(String login, String balanceStage) {
        TestBalanceUtils.setEnvironment(Environment.valueOf(balanceStage));
        Double result = TestBalanceUtils.getClientOverdraft(
                TestBalanceUtils.getClientIdByLogin(login), SERVICE_ID, FIRM_ID);
        return String.valueOf(result);
    }

    public String getAvailableOverdraft(String login, int orderID, String balanceStage) {
        UnitTestLib unitTestLib = new UnitTestLib(Environment.valueOf(balanceStage));
        User balanceClient;
        try {
            balanceClient = User.get(login);
        } catch (UserNotFoundException e) {
            balanceClient = new User();
            balanceClient.setLogin(login);
        }
        Object response;
        try {
            response = unitTestLib.getMobilePaysysByPassport(SERVICE_ID, String.valueOf(orderID)
                    , balanceClient.getPassportUID());
        } catch (Exception e) {
            throw new DirectAPIException("Ошибка получения информации об овердрафте из Баланса", e);
        }
        HashMap<String, Object> result = (HashMap<String, Object>) response;
        HashMap<String, String> overdraftInfo = (HashMap<String, String>) result.get("overdraft");
        Object[] currencies = (Object[]) result.get("currencies");
        return overdraftInfo.get("available_sum") + " " + currencies[0];
    }

}
