/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * Special Declaration:  These technical material reserved as the technical secrets by AGREE
 * TECHNOLOGY have been protected by the "Copyright Law" "ordinances on Protection of Computer
 * Software" and other relevant administrative regulations and international treaties. Without
 * the written permission of the Company, no person may use (including but not limited to the
 * illegal copy, distribute, display, image, upload, and download) and disclose the above
 * technical documents to any third party. Otherwise, any infringer shall afford the legal
 * liability to the company.
 */
import {EventHub} from "event/EventHub";
import {Event} from "event/Event";
import {MessageType} from "event/MessageType";
import {WidgetUtil} from "util/WidgetUtil";
import {Widget} from "widget/Widget";
/**
 * Created by huang.dy on 2016/5/30.
 */
export class DocumentEventInterceptor {
    private static eventTypeMap: Array<number> = new Array();
    private static displayEvents: Array<number> = new Array();
    private static touchStartTimeStamp: number = 0;
    private static touchStartY: number = 0;
    private static touchStartX: number = 0;
    private static touchStartTarget: EventTarget;
    private static touchHadMoved: boolean = false;

    public static addFilter(eventType: number) {
        this.eventTypeMap.push(eventType);
    }

    public static addDisplayEvent(eventType: number) {
        if (this.displayEvents.indexOf(eventType) === -1) {
            this.displayEvents.push(eventType);
        }
    }

    public static removeDisplayEvent(eventType: number) {
        for (let i = 0; i < this.displayEvents.length; i++) {
            if (eventType === this.displayEvents[i]) {
                this.displayEvents.splice(i, 1);
            }
        }
    }

    private static sendDisplayEvent(eventType: number) {
        if (this.displayEvents.indexOf(eventType) !== -1) {
            // 触发DisplayEvent
            EventHub.dispatchEvent(MessageType.DISPLAY, {evtType:  eventType});
        }
    }

    public static initInterceptor() {
        $(document).on("keydown", (e: KeyboardEvent) => {
            //对keydown的拦截监听
            let widget = WidgetUtil.findWidgetByTarget(e.target as HTMLElement);
            if (widget && widget.isEnabled()) {
                if (this.eventTypeMap.indexOf(Event.KEY_DONW) !== -1) {
                    widget.handleKeyDownEvent(e, true);
                } else {
                    widget.handleKeyDownEvent(e, false);
                }
            }
            DocumentEventInterceptor.sendDisplayEvent(Event.KEY_DONW);
        }).on("keyup", (e: KeyboardEvent) => {
            //对keyup拦截监听
            let widget = WidgetUtil.findWidgetByTarget(e.target as HTMLElement);
            if (widget && widget.isEnabled()) {
                widget.handleKeyUpEvent(e);
            }
            DocumentEventInterceptor.sendDisplayEvent(Event.KEY_UP);
        }).on("mousedown", (e: MouseEvent) => {
            //对mousedown的拦截监听
            let widget = WidgetUtil.findWidgetByTarget(e.target as HTMLElement);
            if (widget && widget.isEnabled()) {
                widget.handleMouseDownEvent(e);
            }
            DocumentEventInterceptor.sendDisplayEvent(Event.MOUSE_DOWN);
        }).on("mouseup", (e: MouseEvent, touchToClick: boolean) => {
            //对mouseup拦截监听
            let widget = WidgetUtil.findWidgetByTarget(e.target as HTMLElement);
            if (widget && widget.isEnabled()) {
                if (touchToClick) {
                    e.button = 0;
                }
                widget.handleMouseUpEvent(e);
            }
            DocumentEventInterceptor.sendDisplayEvent(Event.MOUSE_UP);
        }).on("touchmove", (e: TouchEvent) => {
            DocumentEventInterceptor.sendDisplayEvent(Event.TOUCH_MOVE);
        });

        /*
         * 距离很小的拖拽事件识别成点击事件  begin
         * */
        window.addEventListener("touchstart", (e: TouchEvent) => {
            DocumentEventInterceptor.touchStartTimeStamp = e.timeStamp;
            DocumentEventInterceptor.touchStartTarget = e.target;
            DocumentEventInterceptor.touchHadMoved = false;
            DocumentEventInterceptor.touchStartY = e.changedTouches[0].pageY;
            DocumentEventInterceptor.touchStartX = e.changedTouches[0].pageX;
        });

        window.addEventListener("touchmove", (e: TouchEvent) => {
            this.touchHadMoved = true;
        });

        window.addEventListener("touchend", (e: TouchEvent) => {
            if (!this.touchHadMoved || e.target !== this.touchStartTarget) {
                return;
            }
            let changeY = e.changedTouches[0].pageY - DocumentEventInterceptor.touchStartY;
            let changeX = e.changedTouches[0].pageX - DocumentEventInterceptor.touchStartX;
            /**转成非负数**/
            changeX = changeX < 0 ? changeX * -1 :  changeX;
            changeY = changeY < 0 ? changeY * -1 :  changeY;
            let isClick = false;
            let touchTime = e.timeStamp - DocumentEventInterceptor.touchStartTimeStamp;
            if (touchTime <= 900 && changeX <= 80 && changeY <= 80) {
                isClick = true;
            }
            //console.log("touchend  time[" + (touchTime) + "] isClick[" + isClick + "] changeY[" + changeY + "] changeX[" + changeX + "]");
            if (isClick) {
                let widget = WidgetUtil.findWidgetByTarget(e.target as HTMLElement);
                if (widget) {
                    let id: string = widget.getId();
                    if (id.indexOf("TreeItem", 0) !== -1 || id.indexOf("TabItem", 0) !== -1
                        || id.indexOf("MessageDialog", 0) !== -1) {
                        $(e.target).click();
                    } else {
                        $(e.target).trigger("mouseup", "true");
                    }
                } else {
                    $(e.target).click();
                }
            }
        });
        // 距离很小的拖拽事件识别成点击事件  end

    }
}
