import {TSelectObject} from '../types/TSelectObject';
import {IValueObject} from '../interfaces/components/IValueObject';

export class Select implements IValueObject {

    protected html:string = `
        <div class="object-field">
            <label class="form-label js-label"></label>
            <select class="form-control js-select">
                
            </select>
            <div class="invalid-feedback js-error-message"></div>
        </div>
    `;

    protected _template:HTMLElement;

    protected label:HTMLElement;

    protected select:HTMLInputElement;

    protected errorMessage:HTMLElement;

    protected data:TSelectObject;

    protected formKey:string;

    public setFormKey(key:string)
    {
        this.formKey = key;
    }

    public constructor()
    {
        let div = document.createElement('div');
        div.innerHTML = this.html.trim();
        this._template = <HTMLElement>div.firstChild;
        this.label = this._template.querySelector('.js-label');
        this.select = this._template.querySelector('.js-select');
        this.errorMessage = this._template.querySelector('.js-error-message');
    }

    public get template():HTMLElement
    {
        return this._template;
    }

    public loadData(data:TSelectObject)
    {
        this.data = data;
        this.label.innerText = data.description;
        this.select.value = data.value;
        this.select.innerHTML = '';
        for(let option of data.options){
            let isSelected = (data.value == option.value) ? 'selected' : '';
            let div = document.createElement('div');
            div.innerHTML = '<option value="' + option.value + '" ' + isSelected + '>' + option.title + '</option>';
            let opt = div.firstChild;
            this.select.append(opt);
        }
    }

    public showErrors()
    {
        if(this.data.errors.length){
            this.select.classList.add('is-invalid');
            this.errorMessage.innerText = this.data.errors[0];
        }
    }

    public clearErrors()
    {
        this.select.classList.remove('is-invalid');
        this.errorMessage.innerText = '';
    }

    public serialize():TSelectObject
    {
        return this.data;
    }

    public eventsListen()
    {
        this.select.oninput = (e:Event)=>{
            this.data.value = this.select.value;
        };
    }

}