import { Guid } from './../../resources/elements/utilities/guid';
import { observable } from "aurelia-binding";
import { bindable, children, customElement } from "aurelia-templating";
import { UISegmentedOption } from "./ui-segmented-control-option";
import { UIInternal } from '../../utils/ui-internal';

@customElement("ui-segmented-control")
export class UISegmentedControl {
    @observable
    @children('ui-segmented-option')
    options: UISegmentedOption[];
    @bindable
    @observable
    public name: string;
    public selectorPosition: DOMRect;
    public selector: HTMLElement;

    public isUpdatingSelector: boolean = false;

    constructor(protected element: Element) {
        this.name = Guid.newGuid().toString();
    }

    bind() {
        (this.element as HTMLElement).onclick = (ev: PointerEvent) => {
            ev.stopPropagation();
        }
    }

    nameChanged() {
        this.options?.forEach(option => option.name = this.name);
    }

    optionsChanged() {
        this.nameChanged();
        this.initSelector();
        this.options?.forEach(option => option.updateGUI = () => this.translateSelector());
    }

    initSelector() {
        if (this.options?.length > 0 && this.selector != null) {
            this.selector.style.setProperty("width", `${100 / this.options.length}%`);
            this.translateSelector();
        }
    }

    translateSelector() {
        if (!this.isUpdatingSelector) {
            this.isUpdatingSelector = true;
            UIInternal.queueTask(() => {
                if (this.selector != null) {
                    if (this.options.find(x => x.checked == null) || !this.options.find(x => x.checked == x.model)) {
                        this.selector.style.setProperty("display", "none");
                    } else {
                        this.selector.style.removeProperty("display");
                        this.selector.style.transform = `translate(${100 * this.options.findIndex(x => x.checked == x.model)}%)`;
                    }
                }

                this.isUpdatingSelector = false;
            });
        }
    }
}