package com.atlassian.webdriver.bitbucket.element;

import com.atlassian.pageobjects.elements.PageElement;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.ZoneId;
import java.util.Optional;

import static java.util.Optional.ofNullable;
import static org.apache.commons.lang3.StringUtils.stripToNull;

public class TimeZoneSelector extends IdSelect2<TimeZoneSelector, TimeZoneOption> {

    public static final String ID = "s2id_timezone";

    public TimeZoneSelector(@Nonnull PageElement container) {
        super(container, TimeZoneOption.class);
    }

    /**
     * Sets the selector to the default option, which nulls the setting.
     */
    public TimeZoneSelector clearTimeZone() {
        openOptions();
        clearFilter();
        type("Default");
        TimeZoneOption option = findOption(tzOption -> tzOption.getCssClasses().contains("default-option"));
        if (option != null) {
            selectOption(option);
        }

        return self();
    }

    public Optional<ZoneId> getTimeZone() {
        return ofNullable(stripToNull(getSelectedOption().getValue())).map(ZoneId::of);
    }

    public TimeZoneSelector filter(String value) {
        openOptions().type(value);

        return self();
    }

    public TimeZoneSelector setTimeZone(@Nonnull ZoneId zoneId) {
        TimeZoneOption option = findOption(zoneId);
        if (option != null) {
            selectOption(option);
        }

        return self();
    }

    @Nullable
    private TimeZoneOption findOption(@Nonnull ZoneId zoneId) {
        return findOption(optionClass -> zoneId.getId().equals(optionClass.getValue()));
    }

    private TimeZoneOption getSelectedOption() {
        return getSelectedOptions().now().iterator().next();
    }

    @Nonnull
    @Override
    protected TimeZoneSelector self() {
        return this;
    }

}

