import {Directive, ElementRef, HostListener, Input, OnInit, EventEmitter} from "@angular/core";

/**
 * Created by jd on 27/04/2016.
 */

@Directive({
    selector: '[ripple]',
})

export class RippleEffect implements OnInit
{
    ngOnInit():any {

        if(this.rippleReverseCommand != null)
            this.rippleReverseCommand.subscribe((str)=>
            {
                this.showEffect(null);
            });
        return undefined;
    }


    private _el:Element;

    private canAnimate = true;

    @Input()
    rippleReverseCommand:EventEmitter<string>;


    @Input()
    rippleColor:string;

    @Input()
    rippleSize:string;

    @Input()
    rippleMousePosition:boolean;

    constructor(private element:ElementRef)
    {
        this.rippleColor = this.rippleColor || 'white';
        this.rippleSize = this.rippleSize || 'i';//i -> infinity
        this.rippleMousePosition = this.rippleMousePosition || false;
        this._el = element.nativeElement;
    }

    @HostListener('click', ['$event'])
    public showEffect = (event?:MouseEvent) =>
    {
        var newRipple = document.createElement("DIV");

        let time = this.rippleSize == "i" ? 500 : 290;
        // this.cssAnimation.setDuration(10000);
        // this.cssAnimation.addClass('ripple');
        // this.cssAnimation
        //     .setFromStyles({
        //         top: (pos.y - 25) + 'px',
        //         left: (pos.x - 25) + 'px'
        //     });
        //this.cssAnimation.start(newRipple);

        //24/2 = 12
        if (this.rippleMousePosition && event != null)
        {
            var pos = this.getPosition(event);
            newRipple.setAttribute("style", "top:" + (pos.y - 12) + 'px;' + "left:" + (pos.x - 12) + 'px;');
        }
        else
            newRipple.setAttribute("style", "top:" + (this._el.clientTop ) + 'px;' + "left:" + (this._el.clientLeft ) + 'px;');

        newRipple.setAttribute("class", "ripple bg-color-" + this.rippleColor + " size-" + this.rippleSize);
        this._el.appendChild(newRipple);
        setTimeout(() =>
        {
            newRipple.remove();

        }, time);
    };


    private getPosition = (event:MouseEvent):{x:number, y:number} =>
    {
        return {x: event.layerX, y: event.layerY};
    };


}