var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/*! NoSleep.min.js v0.12.0 - git.io/vfn01 - Rich Tibbett - MIT license */
//@ts-ignore
!function (A, e) { "object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.NoSleep = e() : A.NoSleep = e(); }(this, (function () { return function (A) { var e = {}; function B(g) { if (e[g])
    return e[g].exports; var o = e[g] = { i: g, l: !1, exports: {} }; return A[g].call(o.exports, o, o.exports, B), o.l = !0, o.exports; } return B.m = A, B.c = e, B.d = function (A, e, g) { B.o(A, e) || Object.defineProperty(A, e, { enumerable: !0, get: g }); }, B.r = function (A) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(A, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(A, "__esModule", { value: !0 }); }, B.t = function (A, e) { if (1 & e && (A = B(A)), 8 & e)
    return A; if (4 & e && "object" == typeof A && A && A.__esModule)
    return A; var g = Object.create(null); if (B.r(g), Object.defineProperty(g, "default", { enumerable: !0, value: A }), 2 & e && "string" != typeof A)
    for (var o in A)
        B.d(g, o, function (e) { return A[e]; }.bind(null, o)); return g; }, B.n = function (A) { var e = A && A.__esModule ? function () { return A.default; } : function () { return A; }; return B.d(e, "a", e), e; }, B.o = function (A, e) { return Object.prototype.hasOwnProperty.call(A, e); }, B.p = "", B(B.s = 0); }([function (A, e, B) {
        "use strict";
        var g = function () { function A(A, e) { for (var B = 0; B < e.length; B++) {
            var g = e[B];
            g.enumerable = g.enumerable || !1, g.configurable = !0, "value" in g && (g.writable = !0), Object.defineProperty(A, g.key, g);
        } } return function (e, B, g) { return B && A(e.prototype, B), g && A(e, g), e; }; }();
        var o = B(1), E = o.webm, n = o.mp4, C = function () { return "undefined" != typeof navigator && parseFloat(("" + (/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0, ""])[1]).replace("undefined", "3_2").replace("_", ".").replace("_", "")) < 10 && !window.MSStream; }, Q = function () { return "wakeLock" in navigator; }, i = function () { function A() { var e = this; if (function (A, e) { if (!(A instanceof e))
            throw new TypeError("Cannot call a class as a function"); }(this, A), this.enabled = !1, Q()) {
            this._wakeLock = null;
            var B = function () { null !== e._wakeLock && "visible" === document.visibilityState && e.enable(); };
            document.addEventListener("visibilitychange", B), document.addEventListener("fullscreenchange", B);
        }
        else
            C() ? this.noSleepTimer = null : (this.noSleepVideo = document.createElement("video"), this.noSleepVideo.setAttribute("title", "No Sleep"), this.noSleepVideo.setAttribute("playsinline", ""), this._addSourceToVideo(this.noSleepVideo, "webm", E), this._addSourceToVideo(this.noSleepVideo, "mp4", n), this.noSleepVideo.addEventListener("loadedmetadata", (function () { e.noSleepVideo.duration <= 1 ? e.noSleepVideo.setAttribute("loop", "") : e.noSleepVideo.addEventListener("timeupdate", (function () { e.noSleepVideo.currentTime > .5 && (e.noSleepVideo.currentTime = Math.random()); })); }))); } return g(A, [{ key: "_addSourceToVideo", value: function (A, e, B) { var g = document.createElement("source"); g.src = B, g.type = "video/" + e, A.appendChild(g); } }, { key: "enable", value: function () { var A = this; return Q() ? navigator.wakeLock.request("screen").then((function (e) { A._wakeLock = e, A.enabled = !0, console.log("Wake Lock active."), A._wakeLock.addEventListener("release", (function () { console.log("Wake Lock released."); })); })).catch((function (e) { throw A.enabled = !1, console.error(e.name + ", " + e.message), e; })) : C() ? (this.disable(), console.warn("\n        NoSleep enabled for older iOS devices. This can interrupt\n        active or long-running network requests from completing successfully.\n        See https://github.com/richtr/NoSleep.js/issues/15 for more details.\n      "), this.noSleepTimer = window.setInterval((function () { document.hidden || (window.location.href = window.location.href.split("#")[0], window.setTimeout(window.stop, 0)); }), 15e3), this.enabled = !0, Promise.resolve()) : this.noSleepVideo.play().then((function (e) { return A.enabled = !0, e; })).catch((function (e) { throw A.enabled = !1, e; })); } }, { key: "disable", value: function () { Q() ? (this._wakeLock && this._wakeLock.release(), this._wakeLock = null) : C() ? this.noSleepTimer && (console.warn("\n          NoSleep now disabled for older iOS devices.\n        "), window.clearInterval(this.noSleepTimer), this.noSleepTimer = null) : this.noSleepVideo.pause(), this.enabled = !1; } }, { key: "isEnabled", get: function () { return this.enabled; } }]), A; }();
        A.exports = i;
    }, function (A, e, B) {
        "use strict";
        A.exports = { webm: "data:video/webm;base64, ", mp4: "data:video/mp4;base64, " };
    }]); }));
const ws = new WebSocket(`ws://${location.host.split(':')[0]}:{{PORT}}/`);
let imgTmp;
function preventSleep() {
    //@ts-ignore
    var noSleep = new NoSleep();
    document.addEventListener('click', function enableNoSleep() {
        document.removeEventListener('click', enableNoSleep, false);
        noSleep.enable();
        document.getElementById('nosleep').remove();
    }, false);
}
function fullScreen() {
    document.addEventListener('click', function enableFullScreen() {
        const elem = document.querySelector('body');
        document.removeEventListener('click', enableFullScreen, false);
        if (elem.requestFullscreen) {
            elem.requestFullscreen();
            //@ts-ignore
        }
        else if (typeof elem.webkitRequestFullscreen !== 'undefined') { /* Safari */
            //@ts-ignore
            elem.webkitRequestFullscreen();
            //@ts-ignore
        }
        else if (typeof elem.msRequestFullscreen !== 'undefined') { /* IE11 */
            //@ts-ignore
            elem.msRequestFullscreen();
        }
    }, false);
}
function displayMode() {
    fullScreen();
    preventSleep();
}
function setImage(src) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
            imgTmp = new Image();
            let img = document.getElementById('img');
            let body = document.querySelector('body');
            body.className = '';
            body.classList.add('image');
            imgTmp.onload = function () {
                img.style.backgroundImage = `url('${src}')`;
                return resolve(src);
            };
            imgTmp.src = src;
        }));
    });
}
function onImage(arg) {
    return __awaiter(this, void 0, void 0, function* () {
        return setImage(arg.image);
    });
}
function onMeter(arg) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log('meter');
        const body = document.querySelector('body');
        body.className = '';
        body.classList.add('meter');
    });
}
function onBlank(arg) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log('blank');
        const body = document.querySelector('body');
        body.className = '';
        body.classList.add('blank');
    });
}
function onFocus(arg) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log('focus');
        const can = document.getElementById('can');
        const dpr = window.devicePixelRatio || 1;
        let ctx;
        const body = document.querySelector('body');
        body.className = '';
        if (!can.classList.contains('show')) {
            can.classList.add('show');
        }
        can.width = window.innerWidth * dpr;
        can.height = window.innerHeight * dpr;
        can.style.width = `${window.innerWidth}px`;
        can.style.height = `${window.innerHeight}px`;
        ctx = can.getContext('2d');
        ctx.scale(dpr, dpr);
        try {
            yield drawFocus(can, ctx);
        }
        catch (err) {
            alert(JSON.stringify(err));
        }
    });
}
function drawFocus(can, ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const count = 20;
        const half = Math.round(count / 2);
        const dpr = window.devicePixelRatio || 1;
        const w = can.width / dpr;
        const h = can.height / dpr;
        const longest = w >= h ? w * 1.5 : h * 1.5;
        const opp = Math.tan(360 / (count * 32)) * longest / 10;
        for (let i = 0; i < count; i++) {
            ctx.beginPath();
            ctx.moveTo(w / 2, h / 2);
            ctx.lineTo((w / 2) + opp, longest);
            ctx.lineTo((w / 2) - opp, longest);
            ctx.fill();
            ctx.translate(w / 2, h / 2);
            ctx.rotate((360 / count) * Math.PI / 180);
            ctx.translate(-w / 2, -h / 2);
        }
    });
}
function onField(arg) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log('field guide');
        const can = document.getElementById('can');
        const dpr = window.devicePixelRatio || 1;
        const screen = window.outerWidth / window.outerHeight;
        const body = document.querySelector('body');
        body.className = '';
        let ctx;
        if (!can.classList.contains('show')) {
            can.classList.add('show');
        }
        if (arg.ratio) {
            if (arg.ratio < screen) {
                can.width = (window.innerHeight * arg.ratio) * dpr;
                can.height = window.innerHeight * dpr;
            }
            else {
                can.width = window.innerWidth * dpr;
                can.height = (window.innerWidth / arg.ratio) * dpr;
            }
        }
        else {
            can.width = window.innerWidth * dpr;
            can.height = window.innerHeight * dpr;
        }
        if (arg.ratio) {
            if (arg.ratio < screen) {
                can.style.width = `${window.innerHeight * arg.ratio}px`;
                can.style.height = `${window.innerHeight}px`;
            }
            else {
                can.style.width = `${window.innerWidth}px`;
                can.style.height = `${window.innerWidth / arg.ratio}px`;
            }
        }
        else {
            can.style.width = `${window.innerWidth}px`;
            can.style.height = `${window.innerHeight}px`;
        }
        ctx = can.getContext('2d');
        ctx.scale(dpr, dpr);
        try {
            yield drawField(can, ctx);
        }
        catch (err) {
            alert(JSON.stringify(err));
        }
    });
}
// draw a field guide
function drawField(can, ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const count = 20;
        const half = Math.round(count / 2);
        const dpr = window.devicePixelRatio || 1;
        const w = can.width / dpr;
        const h = can.height / dpr;
        const wsec = w / count;
        const hsec = h / count;
        const spacer = 12;
        const fontSize = 18;
        ctx.lineWidth = 2;
        ctx.moveTo(w / 2, 0);
        ctx.lineTo(w / 2, h);
        ctx.stroke();
        ctx.moveTo(0, h / 2);
        ctx.lineTo(w, h / 2);
        ctx.stroke();
        for (let i = 0; i < count; i++) {
            ctx.moveTo(wsec * i, hsec * i);
            ctx.lineTo(wsec * i, h - (hsec * i));
            ctx.stroke();
            ctx.moveTo(wsec * i, hsec * i);
            ctx.lineTo(w - (wsec * i), hsec * i);
            ctx.stroke();
        }
        ctx.lineWidth = 1;
        ctx.font = `${fontSize}px Arial`;
        for (let i = 0; i < half; i++) {
            //left count
            ctx.fillText(`${(half - i)}`, (wsec * i) + spacer, (h / 2) - spacer);
            //right count
            ctx.fillText(`${(half - i)}`, (w - (wsec * i)) - (spacer * 2), (h / 2) + (spacer * 2));
            //up count
            ctx.fillText(`${(half - i)}`, (w / 2) + spacer, (hsec * i) + spacer + (fontSize / 2));
            //down count
            ctx.fillText(`${(half - i)}`, (w / 2) - (spacer * 2), (h - (hsec * i)) - spacer);
        }
    });
}
//keep connection alive
function onPing(arg) {
    return __awaiter(this, void 0, void 0, function* () {
        //console.log('ping')
        return true;
    });
}
function send(obj) {
    if (ws) {
        ws.send(JSON.stringify(obj));
    }
}
let actions = {
    mcopy: (arg) => __awaiter(this, void 0, void 0, function* () { console.log('Connected'); return true; }),
    image: onImage,
    field: onField,
    meter: onMeter,
    focus: onFocus,
    ping: onPing
};
ws.onmessage = (event) => __awaiter(this, void 0, void 0, function* () {
    const req = JSON.parse(event.data);
    let res;
    if (typeof actions[req.action] !== 'undefined') {
        try {
            yield actions[req.action](req);
        }
        catch (err) {
            console.error(err);
        }
        res = {
            action: req.action,
            id: req.id
        };
        send(res);
    }
});
ws.onclose = (event) => __awaiter(this, void 0, void 0, function* () {
    console.log('Connection closed');
});
(function main() {
    displayMode();
})();
//# sourceMappingURL=index.js.map