/**
 * Created by jd on 02/02/2016.
 */
import {Component, ViewEncapsulation, Input, OnInit, Output, EventEmitter} from "@angular/core";
import {Observer} from "rxjs/Observer";
import {Observable} from "rxjs/Observable";
import {CoreProgress} from "../core-progress/core-progress";


@Component(
    {
        selector: "core-image",
        encapsulation: ViewEncapsulation.None,
        templateUrl: "node_modules/bia-framework/components/core-image/core-image.template.html",
        styleUrls: [ 'node_modules/bia-framework/components/core-image/core-image.style.css' ],
        directives: [ CoreProgress ]
    }
)
export class CoreImage implements OnInit {

    private id :string;
    private isProcessing :boolean;

    @Input()
    source :string;

    @Output()
    onChangeSource = new EventEmitter();

    @Input()
    public size :string;

    @Input()
    public type :string;

    @Input("read-only")
    readOnly :boolean;

    constructor() {
        this.id = Math.random().toString(36).slice(-5);
    }

    ngOnInit() :any {
        this.source = this.source || "./img/user.svg";
        return undefined;
    }

    public onHolderClick = () :void => {
        console.log("holder clicked!");
    };

    public onImageChange = ( event :Event ) :void => {

        this.ChangeImage(event).subscribe();

    };


    public ChangeImage = ( event :Event ) :Observable<boolean> => {
        var observable = Observable.create(( observer :Observer<boolean> ) => {
            this.isProcessing = true;


            var t = <HTMLInputElement>event.target;
            var file = t.files[ 0 ];


            var reader = new FileReader();
            reader.onload = ( e :any ) :void => {
                setTimeout(()=> {
                    this.source = e.target.result;
                    this.isProcessing = false;
                    observer.complete();
                }, 1000);


            };
            if ( file != null )
                reader.readAsDataURL(file);

        });

        return observable;


    };

}