/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * 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 {Widget} from "widget/Widget";
import {ADORE} from "ADORE";

/**
 * Recreated by tangqianchong on 2016/7/28.
 */

export class Clock extends Widget {

    private $clockNode: JQuery;
    private intervalId: number;
    //主要高度,默认为300px
    private clockHeight: number = 300;
    //默认scale(1)时的clockBody的高度和宽度
    private DefaultClockSideLengthGS: number = 300;

    private static ClockTemplateLS: string = `
    <div style="display: flex;align-items: center;justify-content: center;width: 100%">
        <nobr class="adore_label" style="width:100%"></nobr>
    </div>
    `;
    private static ClockTemplateGS: string = `
    <div style="display: flex;align-items: center;justify-content: center;width: 100%">
        <div class="clock-GS-main">
            <div class="clock-GS-body">
                 <div class="clock-GS-panel"></div>
                 <div class="clock-GS-hour-anchor">
                    <div class="clock-GS-hour-rotate">
                          <div class="clock-GS-hour-thinhand"></div>
                          <div class="clock-GS-hour-fathand"></div>
                    </div>
                 </div>
                 <div class="clock-GS-minute-anchor">
                    <div class="clock-GS-minute-rotate">
                         <div class="clock-GS-minute-thinhand"></div>
                         <div class="clock-GS-minute-fathand"></div>
                    </div>
                 </div>
                 <div class="clock-GS-second-anchor">
                    <div class="clock-GS-second-rotate">
                        <div class="clock-GS-second-hand"></div>
                    </div>
                 </div>
            </div>
        </div>
    </div>
    `;


    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        if (style === ADORE.Normal) {
            this.$thisNode = $(Clock.ClockTemplateLS).attr({ id: this.id });
            this.$clockNode = this.$thisNode.find("nobr");
            //construct functions
            this.setFontSize = this.setFontSizeLS;
            this.setAlignment = this.setAlignmentLS;
            this.startRedrawClock = this.startRedrawClockLS;
            this.setClockHeight = function (args: { height: number }) { };
            //use functions
            this.startRedrawClock();
        }
        else if ((style & ADORE.Graphics) === ADORE.Graphics) {
            this.$thisNode = $(Clock.ClockTemplateGS).attr({ id: this.id });
            //construct functions
            this.setFontSize = function (args: { fontSize: string }) { };
            this.setAlignment = function (args: { alignment: string }) { };
            this.startRedrawClock = function () { };
            this.setClockHeight = this.setClockHeightGS;
        }
        //重写dispose方法，在dispose时去掉document中加载了的逐时方法
        this.dispose = this.disposeClock;
    }
    //public function accessed by java layer
    public setFontSize: (args: { fontSize: string }) => void;
    public setAlignment: (args: { alignment: string }) => void;
    public setClockHeight: (args: { height: number }) => void;
    private startRedrawClock: () => void;

    // LS:label style
    private setFontSizeLS(args: { fontSize: string }) {
        this.$clockNode.css({ fontSize: args.fontSize });
    }
    private setAlignmentLS(args: { alignment: string }) {
        this.$clockNode.css({ textAlign: args.alignment });
    }
    private startRedrawClockLS() {
        let own = this;
        this.intervalId = setInterval(function () { own.redrawClockOnceLS(own); }, 1000);
    }
    private redrawClockOnceLS(own: any) {
        let currentDate: Date = new Date();
        let clockText: string;
        clockText = `${currentDate.getFullYear()}-${+currentDate.getMonth() + 1}-${currentDate.getDate()} ${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;
        own.$clockNode.get(0).innerHTML = clockText;
    }
    //GS:graphics style
    //绘制graphics style时的表盘
    private createClockPanelGS() {
        let mainGS: JQuery = this.$thisNode.find(".clock-GS-main");
        let bodyGS: JQuery = this.$thisNode.find(".clock-GS-body");
        let panelGS: JQuery = this.$thisNode.find(".clock-GS-panel");

        let own = this;

        this.$thisNode.css("height", this.clockHeight + "px");
        let shortSideLength: number = Math.min(this.$thisNode.get(0).clientWidth, this.$thisNode.get(0).clientHeight);

        mainGS.css({ width: this.DefaultClockSideLengthGS + "px", height: this.DefaultClockSideLengthGS + "px" });
        mainGS.css("transform", `scale(${(shortSideLength / this.DefaultClockSideLengthGS)})`);


        let createMinuteLine = function (angle: number) {
            let anchor: JQuery = $("<div>").add("clock-GS-anchor");
            let minuteLine: JQuery = $("<div>").addClass("clock-GS-minuteLine");
            let radius: number = own.DefaultClockSideLengthGS / 2 * 0.8;
            anchor.css("transform", `rotate(${angle}deg)`);
            minuteLine.css("transform", `translate(-50%,-100%) translateY(-${radius}px)`);
            anchor.append(minuteLine);
            panelGS.append(anchor);
        };

        let createMinuteText = function (angle: number) {
            let minuteText: JQuery = $("<div>").addClass("clock-GS-minuteText");
            let radius: number = own.DefaultClockSideLengthGS / 2 * 0.84;
            //弧度
            let topOffset: number = 0 - Math.cos(angle * Math.PI / 180) * radius;
            let leftOffset: number = Math.sin(angle * Math.PI / 180) * radius;

            minuteText.get(0).innerHTML = `${angle / 6}`;
            minuteText.css({ top: topOffset + "px", left: leftOffset + "px" });
            panelGS.append(minuteText);
        };

        let createHourText = function (angle: number) {
            let hourText: JQuery = $("<div>").addClass("clock-GS-hourText clock-GS-hour" + angle / 30);
            let radius: number = own.DefaultClockSideLengthGS / 2 * 0.65;
            let topOffset: number = 0 - Math.cos(angle * Math.PI / 180) * radius;
            let leftOffset: number = Math.sin(angle * Math.PI / 180) * radius;

            hourText.get(0).innerHTML = `${angle / 30}`;
            hourText.css({ top: topOffset + "px", left: leftOffset + "px" });
            panelGS.append(hourText);
        };


        for (let angle = 1; angle <= 360; angle++) {
            if (angle % 6 === 0) {
                if (angle % 30 === 0) {
                    createMinuteText(angle);
                    createHourText(angle);
                } else {
                    createMinuteLine(angle);
                }
            }
        }
    }

    //初始化指针位置
    private createClockAnchorGS() {
        let hourAnchor: JQuery = this.$thisNode.find(".clock-GS-hour-anchor");
        let minuterAnchor: JQuery = this.$thisNode.find(".clock-GS-minute-anchor");
        let secondAnchor: JQuery = this.$thisNode.find(".clock-GS-second-anchor");
        let now: Date = new Date();
        //将当前时间从0点或12开始的时间差距转化成以秒为计时单位的定量
        let seconds: number = (now.getHours() >= 12 ? now.getHours() - 12 : now.getHours()) * 3600 + now.getMinutes() * 60 + now.getSeconds();
        let hourRotateAngle: number = seconds / 120;
        let minuteRotateAngle: number = (seconds / 10) % 360;
        let secondRotateAngle: number = (seconds * 6) % 360;
        hourAnchor.css("transform", `rotate(${hourRotateAngle}deg)`);
        minuterAnchor.css("transform", `rotate(${minuteRotateAngle}deg)`);
        secondAnchor.css("transform", `rotate(${secondRotateAngle}deg)`);
    }

    private setClockHeightGS(args: { height: number }) {
        this.clockHeight = args.height;
        this.$thisNode.css("height", this.clockHeight + "px");
        //如果已经layout完成则需要重置scale大小
        let shortSideLength = Math.min(this.$thisNode.get(0).clientWidth, this.$thisNode.get(0).clientHeight);
        if (shortSideLength !== 0) {
            this.$thisNode.find(".clock-GS-panel").css("transform", `scale(${shortSideLength / this.DefaultClockSideLengthGS})`);
        }
    }

    public postLayout() {
        this.createClockPanelGS();
        this.createClockAnchorGS();
    }

    private disposeClock() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
        super.dispose();
    }
}
