/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */

import {Component, ElementRef, Input} from '@angular/core';
import {NG_VALUE_ACCESSOR} from '@angular/forms';
import {InputAccessor} from '../input-accessor';

export interface UiSelectOption {
    id: any;
    caption: string;
}

@Component({
    selector: 'ui-select',
    template: require('./ui-select.html'),
    styles: [require('./ui-select.less')],
    providers: [
        {provide: NG_VALUE_ACCESSOR, useExisting: UiSelect, multi: true}
    ]
})
export class UiSelect extends InputAccessor {

    @Input() list: UiSelectOption[];

    private caption;

    constructor(public elementRef: ElementRef) {
        super();
    }

    public prepareValueHook() {}

    public updateCaption() {
        if (!this.list)
            return;
        for (let item of this.list) {
            if (item.id === this.innerValue) {
                this.caption = item.caption;
                break;
            }
        }
    }

    get innerValue(): any {
        return this._innerValue;
    }

    set innerValue(value: any) {
        super.updateValue(value);
        this.updateCaption();
    }

}
