import {  AfterContentInit, Injectable, EventEmitter } from "@angular/core";
import { Validators } from "@angular/common";
import { CoreForm } from "./odisseia-form";
import { CoreControl } from "./CoreControl";

/**
 * Created by jd on 29/04/2016.
 */

@Injectable()
export class CoreControlFormBase implements AfterContentInit
{

    //states   
    isProcessing:boolean = false;

    name:string;
    bind:Object;
    bindChange:EventEmitter<Object>;

    controlValidators:Array<any>;
    validationList:Array<ValidationMessage>;

    control:CoreControl;


    ngAfterContentInit():any
    {
        if (this.formHost != null)
        {
            this.control = new CoreControl(this.bind, Validators.compose(this.controlValidators));
            this.control.valueChanges.subscribe(a =>
            {
                this.controlValueChange(a);
                this.bindChange.emit(a);
            });
            this.controlValueChange(this.bind);
            this.formHost.addControl(this.name, this.control);
        }

        return undefined;
    }

    public setupBind = ( _name:string,
                         _bind:Object,
                         _bindChange:EventEmitter<Object> ):void =>
    {
        this.name = _name;
        this.bind = _bind;
        this.bindChange = _bindChange;

    };

    constructor( private formHost?:CoreForm )
    {
        this.controlValidators = [];
        this.validationList = [];
    }

    public OnFocus = ():void =>
    {
        this.control.focused = true;

    };

    public OnBlur = ():void =>
    {
        this.control.focused = false;
        this.control.wasTouched = true;
    };

    public OnChange = ( a ):void =>
    {
        this.control.updateValue(a);


    };

    public isInForm = ():boolean =>
    {
        return this.formHost != null;
    };

    public addFormValidator = ( validationDesc:ValidationMessage, validator:any ) =>
    {
        this.controlValidators.push(validator);
        this.validationList.push(validationDesc);
    };

    public controlValueChange = ( v:any ):void =>
    {
        if (v != null && v != "")
            this.control.hasValue = true;
        else
            this.control.hasValue = false;
    };

}