import { Directive, ElementRef, OnInit, OnDestroy, Output, EventEmitter } from "@angular/core";
import { Gesture } from "ionic-angular/gestures/gesture";

@Directive({
    selector: "[doubleTap]"
})
export class DoubleTap implements OnInit, OnDestroy {

    el: HTMLElement;
    tapGesture: Gesture;
    lastTimeStamp: number = 0;

    @Output()    
    doubleTap: EventEmitter<any> = new EventEmitter();

    constructor(el: ElementRef) {
        this.el = el.nativeElement;
     }    

    /**
     *
     */
    ngOnInit() {
        this.tapGesture = new Gesture(this.el);
        this.tapGesture.listen();
        this.tapGesture.on("tap", e => {
            if (this.lastTimeStamp == 0) {
                this.lastTimeStamp = e.timeStamp;
                return;
            }

            let delay = e.timeStamp - this.lastTimeStamp;
            this.lastTimeStamp = 0;

            if (delay <= 500) {
                this.doubleTap.emit(e);
            }
        });
    }   
    

    /**
     *
     */
    ngOnDestroy() {
        this.tapGesture.destroy();
    }
}