package ru.yandex.autotests.direct.web.pages.banners.blocks.edit;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.yandex.autotests.direct.web.objects.banners.commons.ContactInfoWeb;
import ru.yandex.autotests.direct.web.pages.ExtendedHtmlElement;
import ru.yandex.autotests.direct.web.util.testinterfaces.IWebFrom;
import ru.yandex.autotests.direct.web.webelements.TimePeriodInput;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Link;
import ru.yandex.qatools.htmlelements.element.Select;
import ru.yandex.qatools.htmlelements.element.TextInput;

import static ch.lambdaj.Lambda.on;
import static org.hamcrest.MatcherAssert.assertThat;
import static ru.yandex.autotests.direct.utils.matchers.BeanEquals.beanEquals;
import static ru.yandex.autotests.direct.web.util.OperationSystemUtils.sleep;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillTextInput;
import static ru.yandex.autotests.direct.web.util.beanutils.BeanFieldsSetter.inAccordanceWith;
import static ru.yandex.qatools.htmlelements.matchers.WrapsElementMatchers.exists;

/**
 * @author Roman Kuhta (kuhtich@yandex-team.ru)
 */
@FindBy(xpath = ".//tbody[contains(@class, 'b-vcard-form')]")
public class AddressAndPhoneBlock extends ExtendedHtmlElement implements IWebFrom<ContactInfoWeb> {
    private static final String NEW_OGRN_TEXT = "-- новый --";
    @Name("Ссылка 'очистить контактную информацию'")
    @FindBy(xpath = ".//a[@class='b-vcard-form-copy__clear-link']")
    private Link clearAllLink;

    @Name("Поле ввода страны")
    @FindBy(xpath = ".//span[contains(@class, 'place__country')]//input")
    private TextInput country;

    @Name("Поле ввода города")
    @FindBy(xpath = ".//span[contains(@class, 'place__city')]//input")
    private TextInput city;

    @Name("Поле ввода кода страны")
    @FindBy(xpath = ".//input[contains(@id, 'country_code')]")
    private TextInput countryCode;

    @Name("Поле ввода кода города")
    @FindBy(xpath = ".//*[contains(@id, 'city_code')]")
    private TextInput cityCode;

    @Name("Поле ввода номера телефона")
    @FindBy(xpath = ".//input[starts-with(@id, 'phone')]")
    private TextInput phone;

    @Name("Поле ввода добавочного номера телефона")
    @FindBy(xpath = ".//span[contains(@class, 'form__ext')]//input")
    private TextInput phoneExt;

    @Name("Поле ввода имени компании")
    @FindBy(xpath = ".//span[contains(@class, 'form__name')]//input")
    private TextInput companyName;

    @Name("Поле ввода ФИО")
    @FindBy(xpath = ".//span[contains(@class, 'contactperson')]//input")
    private TextInput contactPerson;

    private List<TimePeriodInput> workingTimeList;

    @Name("Поле ввода улицы")
    @FindBy(xpath = ".//span[contains(@class, 'street')]//input")
    private TextInput street;

    @Name("Поле ввода номера дома")
    @FindBy(xpath = ".//span[contains(@class, 'house')]//input")
    private TextInput house;

    @Name("Поле ввода номера строения")
    @FindBy(xpath = ".//span[contains(@class, 'build')]//input")
    private TextInput build;

    @Name("Поле ввода номера офиса/квартиры")
    @FindBy(xpath = ".//span[contains(@class, 'apart')]//input")
    private TextInput apart;

    @Name("Поле ввода email")
    @FindBy(xpath = ".//span[contains(@class, 'contact-email')]//input")
    private TextInput contactEmail;

    @Name("Селект IM")
    @FindBy(xpath = ".//select[contains(@class, 'im_client')]")
    private Select IMClient;

    @Name("Поле ввода логина IM")
    @FindBy(xpath = ".//span[contains(@class, 'im_login')]//input")
    private TextInput IMLogin;

    @Name("Поле ввода дополнительной информации")
    @FindBy(xpath = ".//span[contains(@class, 'extra-message')]//textarea")
    private TextInput extraMessage;

    @Name("Поле ввода ОГРН")
    @FindBy(xpath = ".//span/input[contains(@class, 'ogrn')]")
    private TextInput OGRNTextInput;

    @Name("Селект ОГРН")
    @FindBy(xpath = ".//select[contains(@class, 'b-ogrn-input__org-details')]")
    private Select OGRNSelect;

    public String getPhoneNumber() {
        return phone.getText().replace("-", "");
    }

    public String getWorkTime() {
        LinkedList<String> valuesList = new LinkedList<>();
        for (TimePeriodInput workingTime : workingTimeList) {
            valuesList.add(workingTime.periodStartDaySelect.getFirstSelectedOption().getAttribute("value"));
            valuesList.add(workingTime.periodEndDaySelect.getFirstSelectedOption().getAttribute("value"));
            valuesList.add(workingTime.periodStartTimeInHoursSelect.getFirstSelectedOption().getAttribute("value"));
            valuesList.add(workingTime.periodStartTimeInMinutesSelect.getFirstSelectedOption().getAttribute("value"));
            valuesList.add(workingTime.periodEndTimeInHoursSelect.getFirstSelectedOption().getAttribute("value"));
            valuesList.add(workingTime.periodEndTimeInMinutesSelect.getFirstSelectedOption().getAttribute("value"));
        }
        return StringUtils.join(valuesList, ";").replace("00", "0");
    }

    private void fillSelect(Select select, String val) {
        if (val == null)
            return;
        select.selectByValue(val);
    }

    private void fillWorkTime(String period) {
        if (period == null)
            return;
        String[] timeValues = period.split(";");
        addWorkingHours(timeValues.length / 6);
        int timeValueCounter = 0;
        for (String timeValue : timeValues) {
            TimePeriodInput block = workingTimeList.get(timeValueCounter / 6);
            switch (timeValueCounter % 6) {
                case 0:
                    fillSelect(block.periodStartDaySelect, timeValue);
                    break;
                case 1:
                    fillSelect(block.periodEndDaySelect, timeValue);
                    break;
                case 2:
                    fillSelect(block.periodStartTimeInHoursSelect, timeValue);
                    break;
                case 3:
                    if (timeValue.equals("0"))
                        timeValue = "00";
                    fillSelect(block.periodStartTimeInMinutesSelect, timeValue);
                    break;
                case 4:
                    fillSelect(block.periodEndTimeInHoursSelect, timeValue);
                    break;
                case 5:
                    if (timeValue.equals("0"))
                        timeValue = "00";
                    fillSelect(block.periodEndTimeInMinutesSelect, timeValue);
                    break;
            }
            timeValueCounter++;
        }
    }

    private void addWorkingHours(int count) {
        if (workingTimeList.size() == count)
            return;
        if (workingTimeList.size() > count) {
            for (int i = workingTimeList.size() - 1; i > count - 1; i--) {
                workingTimeList.get(i).removeWorkingTimeButton.click();
            }
        }
        if (workingTimeList.size() < count) {
            for (int i = workingTimeList.size() - 1; i < count - 1; i++) {
                workingTimeList.get(i).addWorkingTimeButton.click();
            }
        }
    }

    public void fillStreet(String street) {
        fillTextInput(this.street, street);
        sleep(3000);
    }

    @Override
    public void fillParameters(ContactInfoWeb bean) {
        fillTextInput(country, bean.getCountry());
        fillTextInput(city, bean.getCity());
        fillTextInput(countryCode, bean.getCountryCode());
        fillTextInput(cityCode, bean.getCityCode());
        fillTextInput(phone, bean.getPhone());
        fillTextInput(phoneExt, bean.getPhoneExt());
        fillTextInput(companyName, bean.getCompanyName());
        fillTextInput(contactPerson, bean.getContactPerson());
        fillWorkTime(bean.getWorkTime());
        fillStreet(bean.getStreet());
        fillTextInput(house, bean.getHouse());
        fillTextInput(build, bean.getBuild());
        fillTextInput(apart, bean.getApart());
        fillTextInput(contactEmail, bean.getContactEmail());
        fillSelect(IMClient, bean.getIMClient());
        fillTextInput(IMLogin, bean.getIMLogin());
        fillTextInput(extraMessage, bean.getExtraMessage());
        fillOGRN(bean.getOGRN());

    }

    private void fillOGRN(String ogrn) {
        if (ogrn == null) {
            return;
        }
        if (exists().matches(OGRNSelect) && OGRNSelect.isDisplayed()) {
            for (WebElement ogrnOption : OGRNSelect.getOptions()) {
                if (ogrnOption.getText().equals(ogrn)) {
                    OGRNSelect.selectByVisibleText(ogrn);
                    return;
                }
            }
            OGRNSelect.selectByVisibleText(NEW_OGRN_TEXT);
        }
        fillTextInput(OGRNTextInput, ogrn);
    }

    public String getOGRN() {
        if (exists().matches(OGRNSelect) && OGRNSelect.isDisplayed()
                && !OGRNSelect.getFirstSelectedOption().getText().equals(NEW_OGRN_TEXT)) {
            return OGRNSelect.getFirstSelectedOption().getText();
        }
        return OGRNTextInput.getText();
    }

    @Override
    public void checkParameters(ContactInfoWeb expectedBean) {
        if (expectedBean != null) {
            assertThat("неверные параметры контактной информации",
                    getFormFieldsAccording(expectedBean), beanEquals(expectedBean));
        }
    }

    @Override
    public ContactInfoWeb getFormFieldsAccording(ContactInfoWeb expectedBean) {
        return inAccordanceWith(expectedBean).forNew(ContactInfoWeb.class)
                .set("country", country, on(TextInput.class).getText())
                .set("city", city, on(TextInput.class).getText())
                .set("countryCode", countryCode, on(TextInput.class).getText())
                .set("cityCode", cityCode, on(TextInput.class).getText())
                .set("phone", this, on(AddressAndPhoneBlock.class).getPhoneNumber())
                .set("phoneExt", phoneExt, on(TextInput.class).getText())
                .set("companyName", companyName, on(TextInput.class).getText())
                .set("contactPerson", contactPerson, on(TextInput.class).getText())
                .set("workTime", this, on(AddressAndPhoneBlock.class).getWorkTime())
                .set("street", street, on(TextInput.class).getText())
                .set("house", house, on(TextInput.class).getText())
                .set("build", build, on(TextInput.class).getText())
                .set("apart", apart, on(TextInput.class).getText())
                .set("contactEmail", contactEmail, on(TextInput.class).getText())
                .set("IMClient", IMClient,
                        on(Select.class).getFirstSelectedOption().getAttribute("value"))
                .set("IMLogin", IMLogin, on(TextInput.class).getText())
                .set("extraMessage", extraMessage,
                        on(TextInput.class).getWrappedElement().getAttribute("value"))
                .set("OGRN", this, on(AddressAndPhoneBlock.class).getOGRN())
                .getActualBean();
    }
}
