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());
    });
};
import { UAParser } from "ua-parser-js";
import { STRINGS, tr } from "./tr";
import { BridgedCameraSource } from "./bridged-camera-source";
let parser = new UAParser();
let _isWebXRSupported = false;
let _permissionGrantedCamera = false;
let _permissionGrantedMotion = false;
let _permissionDeniedCamera = false;
let _permissionDeniedMotion = false;
let _hadOneSuccessfulActivation = false;
if (!window.DeviceOrientationEvent || !window.DeviceOrientationEvent.requestPermission) {
    _permissionGrantedMotion = true;
}
function checkForCameraPermission() {
    return __awaiter(this, void 0, void 0, function* () {
        if (navigator.permissions && navigator.permissions.query) {
            try {
                let res = yield navigator.permissions.query({ name: "camera" });
                _permissionDeniedCamera = res.state === 'denied';
                _permissionGrantedCamera = res.state === 'granted';
            }
            catch (ex) { }
        }
    });
}
checkForCameraPermission();
export function permissionGrantedCamera() {
    var _a;
    if (_isWebXRSupported) {
        return _permissionGrantedCamera && ((_a = navigator.userActivation) === null || _a === void 0 ? void 0 : _a.isActive);
    }
    return _permissionGrantedCamera;
}
export function permissionGrantedMotion() { return _permissionGrantedMotion; }
export function permissionDeniedCamera() { return _permissionDeniedCamera; }
export function permissionDeniedMotion() { return _permissionDeniedMotion; }
export function permissionDeniedAny() { return _permissionDeniedCamera || _permissionDeniedMotion; }
export function permissionGrantedAll() { return permissionGrantedCamera() && _permissionGrantedMotion; }
export function permissionRequestAll() {
    return __awaiter(this, void 0, void 0, function* () {
        yield permissionRequestMotion();
        yield permissionRequestCamera();
    });
}
export function permissionRequestCamera() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            let res = yield navigator.mediaDevices.getUserMedia({
                video: true
            });
            let tracks = res.getTracks();
            tracks.forEach(t => t.stop());
            _permissionGrantedCamera = true;
            _permissionDeniedCamera = false;
        }
        catch (err) {
            _permissionGrantedCamera = false;
            _permissionDeniedCamera = true;
        }
    });
}
export function permissionRequestMotion() {
    return __awaiter(this, void 0, void 0, function* () {
        if (BridgedCameraSource.IsSupported()) {
            _permissionGrantedMotion = true;
            _permissionDeniedMotion = false;
            return;
        }
        if (window.DeviceOrientationEvent && window.DeviceOrientationEvent.requestPermission) {
            let permissionResult = yield window.DeviceOrientationEvent.requestPermission();
            if (permissionResult !== 'granted') {
                _permissionGrantedMotion = false;
                _permissionDeniedMotion = true;
                return false;
            }
        }
        // No motion permissions or granted
        _permissionGrantedMotion = true;
        _permissionDeniedMotion = false;
    });
}
export function permissionRequestUI(options) {
    var _a, _b, _c, _d;
    return __awaiter(this, void 0, void 0, function* () {
        yield checkForCameraPermission();
        if (permissionGrantedAll() && !(options === null || options === void 0 ? void 0 : options.ignoreUserActivation)) {
            return true;
        }
        let div = document.createElement("div");
        div.classList.add("zappar-permission-request");
        div.classList.add("zappar-permission-request-without-button");
        div.innerHTML = `
    <style>
        .zappar-permission-request {
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0px;
            left: 0px;
            z-index: 1000;
            background-color: rgba(0, 0, 0, 0.9);
            font-family: sans-serif;
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .zappar-permission-request-without-button {
            justify-content: flex-start;
        }

        .zappar-permission-request-without-button #zappar-permission-request-button {
            display: none;
        }

        .zappar-permission-request-without-button .zappar-inner {
            max-width: 300px;
        }

        .zappar-inner {
            margin-top: 30%;
            margin-bottom: 30%;
            max-width: 400px;
            text-align: center;
        }
        .zappar-title {
            font-size: 20px;
        }
        .zappar-text {
            font-size: 14px;
            padding: 15px;
        }
        .zappar-inner > button {
            background: none;
            outline: none;
            border: 2px solid white;
            border-radius: 10px;
            color: white;
            padding: 10px 40px;
            text-transform: uppercase;
        }
    </style>
    <div class="zappar-inner">
        <div class="zappar-title">${(_a = options === null || options === void 0 ? void 0 : options.title) !== null && _a !== void 0 ? _a : tr(STRINGS.PermissionTitle)}</div>
        <div class="zappar-text">${(_b = options === null || options === void 0 ? void 0 : options.description) !== null && _b !== void 0 ? _b : tr(STRINGS.PermissionDescription)}</div>
        <button id="zappar-permission-request-button">${(_c = options === null || options === void 0 ? void 0 : options.button) !== null && _c !== void 0 ? _c : tr(STRINGS.PermissionButton)}</button>
    </div>
`;
        document.body.append(div);
        function attempt() {
            return __awaiter(this, void 0, void 0, function* () {
                yield permissionRequestAll();
                div.remove();
                while (true) {
                    yield nextFrame();
                    if (permissionDeniedAny()) {
                        return false;
                    }
                    if (permissionGrantedAll()) {
                        _hadOneSuccessfulActivation = true;
                        return true;
                    }
                }
                return false;
            });
        }
        try {
            if (_isWebXRSupported && (!((_d = navigator.userActivation) === null || _d === void 0 ? void 0 : _d.isActive) || _hadOneSuccessfulActivation))
                throw new Error("WebXR - need user interaction");
            return yield attempt();
        }
        catch (err) {
            // We may need a user interaction
            div.classList.remove("zappar-permission-request-without-button");
            let button = div.querySelector("#zappar-permission-request-button");
            return yield new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
                button === null || button === void 0 ? void 0 : button.addEventListener('click', () => __awaiter(this, void 0, void 0, function* () {
                    resolve(yield attempt());
                }));
            }));
        }
    });
}
function nextFrame() {
    return new Promise(resolve => requestAnimationFrame(() => resolve()));
}
export function permissionDeniedUI(options) {
    switch (parser.getBrowser().name) {
        case "Chrome":
            permissionDeniedUIChrome(options);
            break;
        default:
            permissionDeniedUIIOS(options);
            break;
    }
}
function permissionDeniedUIIOS(options) {
    var _a, _b, _c, _d;
    let div = document.createElement("div");
    div.classList.add("zappar-permission-request");
    div.innerHTML = `
    <style>
        .zappar-permission-request {
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0px;
            left: 0px;
            z-index: 1000;
            background-color: rgba(0, 0, 0, 0.9);
            font-family: sans-serif;
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .zappar-inner {
            max-width: 400px;
            text-align: center;
        }
        .zappar-title {
            font-size: 20px;
        }
        .zappar-text {
            font-size: 14px;
            padding: 15px;
        }
        .zappar-inner > button {
            background: none;
            outline: none;
            border: 2px solid white;
            border-radius: 10px;
            color: white;
            padding: 10px 40px;
            text-transform: uppercase;
        }
    </style>
    <div class="zappar-inner">
        <div class="zappar-title">${(_a = options === null || options === void 0 ? void 0 : options.title) !== null && _a !== void 0 ? _a : 'Permission is Needed'}</div>
        <div class="zappar-text">${(_c = (_b = options === null || options === void 0 ? void 0 : options.descriptionIOS) !== null && _b !== void 0 ? _b : options === null || options === void 0 ? void 0 : options.description) !== null && _c !== void 0 ? _c : "Permission to access your device's camera and motion sensors is necessary for this experience. Please reload the page to try again."}</div>
        <button id="zappar-permission-reload-button">${(_d = options === null || options === void 0 ? void 0 : options.button) !== null && _d !== void 0 ? _d : 'Reload'}</button>
    </div>
`;
    document.body.append(div);
    let button = div.querySelector("#zappar-permission-reload-button");
    button === null || button === void 0 ? void 0 : button.addEventListener("click", () => window.location.reload());
}
function permissionDeniedUIChrome(options) {
    var _a, _b, _c, _d;
    let div = document.createElement("div");
    div.classList.add("zappar-permission-request");
    div.innerHTML = `
    <style>
        .zappar-permission-request {
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0px;
            left: 0px;
            z-index: 1000;
            background-color: rgba(0, 0, 0, 0.9);
            font-family: sans-serif;
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .zappar-inner {
            width: 400px;
            text-align: center;
        }
        .zappar-title {
            font-size: 20px;
        }
        .zappar-text {
            font-size: 14px;
            padding: 15px;
        }
        .zappar-inner > button {
            background: none;
            outline: none;
            border: 2px solid white;
            border-radius: 10px;
            color: white;
            padding: 10px 40px;
            text-transform: uppercase;
        }
    </style>
    <div class="zappar-inner">
        <div class="zappar-title">${(_a = options === null || options === void 0 ? void 0 : options.title) !== null && _a !== void 0 ? _a : 'Permission is Needed'}</div>
        <div class="zappar-text">${(_c = (_b = options === null || options === void 0 ? void 0 : options.descriptionChrome) !== null && _b !== void 0 ? _b : options === null || options === void 0 ? void 0 : options.description) !== null && _c !== void 0 ? _c : `Permission to access your device's camera and motion sensors is necessary for this experience.<br/><br/>To grant access, please tap the <svg xmlns="http://www.w3.org/2000/svg" height="16px" viewBox="0 -960 960 960" width="16px" fill="white"><path d="M696-144q-60.48 0-102.24-41.76T552-288q0-60.48 41.76-102.24T696-432q60.48 0 102.24 41.76T840-288q0 60.48-41.76 102.24T696-144Zm.12-72Q726-216 747-237.12q21-21.12 21-51T746.88-339q-21.12-21-51-21T645-338.88q-21 21.12-21 51T645.12-237q21.12 21 51 21ZM168-252v-72h312v72H168Zm96-276q-60.48 0-102.24-41.76T120-672q0-60.48 41.76-102.24T264-816q60.48 0 102.24 41.76T408-672q0 60.48-41.76 102.24T264-528Zm.12-72Q294-600 315-621.12q21-21.12 21-51T314.88-723q-21.12-21-51-21T213-722.88q-21 21.12-21 51T213.12-621q21.12 21 51 21ZM480-636v-72h312v72H480Zm216 348ZM264-672Z"/></svg> button in the address bar of your browser, then "Permissions", and finally "Reset permissions". You can then reload the page to try again.`}</div>
        <button id="zappar-permission-reload-button">${(_d = options === null || options === void 0 ? void 0 : options.button) !== null && _d !== void 0 ? _d : 'Reload'}</button>
    </div>
`;
    document.body.append(div);
    let button = div.querySelector("#zappar-permission-reload-button");
    button === null || button === void 0 ? void 0 : button.addEventListener("click", () => window.location.reload());
}
export function setWebXRSupported(supported) {
    _isWebXRSupported = supported;
}
