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

export class Bool implements IValueObject {

    protected html:string = `
        <div class="object-field form-check">
            <input class="form-check-input js-input" type="checkbox" id="">
            <label class="form-check-label js-label" for=""></label>
            <div class="invalid-feedback js-error-message"></div>
        </div>
    `;

    protected _template:HTMLElement;

    protected label:HTMLElement;

    protected input:HTMLInputElement;

    protected errorMessage:HTMLElement;

    protected data:TValueObject;

    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;
        let id = Symbol();
        this.label = this._template.querySelector('.js-label');
        this.label.setAttribute('for', id.toString());
        this.input = this._template.querySelector('.js-input');
        this.input.setAttribute('id', id.toString());
        this.errorMessage = this._template.querySelector('.js-error-message');
    }

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

    public loadData(data:TValueObject)
    {
        this.data = data;
        this.label.innerText = data.description;
        this.input.checked = data.value;
    }

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

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

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

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

}