import JPlayer from "./jplayer";
import { ControllerOpt, createDefaultControllerOpt, defaultControllerOpt, Streamtype } from "./model/playerModel";
import { createPtzControllerDom } from "./utils/controlDom";
import nipplejs from './utils/nipplejs';
import { getJoysticPositionFlag } from "./utils/ptzController";

class JPtzController {
    private _plyer: JPlayer;
    private toolbox_ele: HTMLDivElement;
    private joystick_ele: HTMLDivElement;
    private joystickIns: any;
    constructor(playerIns: JPlayer, public el: HTMLElement, public controllerOpt: ControllerOpt) {
        this.controllerOpt = { ...(createDefaultControllerOpt() as ControllerOpt), ...controllerOpt }
        this._plyer = playerIns;
        this.bindPlayer();
    }
    bindPlayer() {
        if (this._plyer) {
            this._plyer.on('inited', (vid, playerIns) => {
                const { isptz, streamtype } = playerIns && playerIns.streamOpt;
                this.initDom(isptz, streamtype)
            })
        }
    }
    emptyDom() {
        const c = this.el.childNodes;
        c.forEach(t => {
            t.parentNode.removeChild(t);
        })
    }
    initDom(isPtz, streamtype: Streamtype) {
        const { hideTools } = this.controllerOpt;
        this.emptyDom();
        const [box, toolbox, joystick] = createPtzControllerDom(this._plyer, hideTools, isPtz, streamtype)
        this.el.appendChild(box)
        this.toolbox_ele = toolbox
        this.joystick_ele = joystick
        if (streamtype === 'live' && isPtz) {
            this.initJoystic()
        }
    }
    initJoystic() {
        if (this.joystickIns) {
            this.destroyJoystick()
        }
        const { clientHeight, clientWidth } = this.el;
        const size = Math.min(clientHeight, clientWidth) * 0.8
        const opt = {
            zone: this.joystick_ele,
            mode: 'static',
            position: { left: '50%', top: '50%' },
            jvideo: true,
            size: size
        }
        this.joystickIns = nipplejs.create(opt)
        this.joystickIns.on('dir:up dir:down dir:left dir:right end',
            (evt, data) => {
                if (evt.type === 'end') {
                    setTimeout(() => {
                        this._plyer.sendPtzCmd(-1)
                    }, 26)
                } else {
                    const f = getJoysticPositionFlag(evt.type)
                    this._plyer.sendPtzCmd(f)
                }
            }
        )
    }
    destroyJoystick() {
        if (this.joystickIns) {
            this.joystickIns.destroy()
            this.joystickIns = null
        }
    }
}
export default JPtzController;