import { createApp } from "vue";
import { library } from "@fortawesome/fontawesome-svg-core";
import {
    faEye,
    faThumbtack,
    faCheck,
    faHeart,
    faHeadphones,
    faRss,
    faChevronLeft,
    faLevelDownAlt,
    faTv,
    faLevelUpAlt,
    faBroadcastTower,
    faCirclePlus,
    faCircleMinus,
    faXmark,
    faClone,
    faShare,
} from "@fortawesome/free-solid-svg-icons";
import { faGithub, faBitcoin } from "@fortawesome/free-brands-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
library.add(
    faEye,
    faGithub,
    faBitcoin,
    faThumbtack,
    faCheck,
    faHeart,
    faHeadphones,
    faRss,
    faChevronLeft,
    faLevelDownAlt,
    faLevelUpAlt,
    faTv,
    faBroadcastTower,
    faCirclePlus,
    faCircleMinus,
    faXmark,
    faClone,
    faShare,
);

import router from "@/router/router.js";

import "uno.css";

/*EFY UI*/
import "../efy/efy.css";
import "../efy/piped.css";
import "../efy/efy.js";

import App from "./App.vue";

import DOMPurify from "dompurify";

import TimeAgo from "javascript-time-ago";

import en from "javascript-time-ago/locale/en";

TimeAgo.addDefaultLocale(en);

import { createI18n } from "vue-i18n";
import enLocale from "@/locales/en.json";

const timeAgo = new TimeAgo("en-US");

import("./registerServiceWorker");

const mixin = {
    methods: {
        timeFormat: function (duration) {
            var pad = function (num, size) {
                return ("000" + num).slice(size * -1);
            };

            var time = parseFloat(duration).toFixed(3),
                hours = Math.floor(time / 60 / 60),
                minutes = Math.floor(time / 60) % 60,
                seconds = Math.floor(time - minutes * 60);

            var str = "";

            if (hours > 0) str += hours + ":";

            str += pad(minutes, 2) + ":" + pad(seconds, 2);

            return str;
        },
        numberFormat(num) {
            const digits = 2;
            const si = [
                { value: 1, symbol: "" },
                { value: 1e3, symbol: "k" },
                { value: 1e6, symbol: "M" },
                { value: 1e9, symbol: "B" },
            ];
            const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
            for (var i = si.length - 1; i > 0; i--) {
                if (num >= si[i].value) {
                    break;
                }
            }
            return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
        },
        addCommas(num) {
            num = parseInt(num);
            return num.toLocaleString("en-US");
        },
        fetchJson: function (url, params, options) {
            if (params) {
                url = new URL(url);
                for (var param in params) url.searchParams.set(param, params[param]);
            }
            return fetch(url, options).then(response => {
                return response.json();
            });
        },
        purifyHTML(original) {
            return DOMPurify.sanitize(original);
        },
        setPreference(key, value) {
            if (localStorage) localStorage.setItem(key, value);
        },
        getPreferenceBoolean(key, defaultVal) {
            var value;
            if (
                (value = new URLSearchParams(window.location.search).get(key)) !== null ||
                (this.testLocalStorage && (value = localStorage.getItem(key)) !== null)
            ) {
                switch (String(value).toLowerCase()) {
                    case "true":
                    case "1":
                    case "on":
                    case "yes":
                        return true;
                    default:
                        return false;
                }
            } else return defaultVal;
        },
        getPreferenceString(key, defaultVal) {
            var value;
            if (
                (value = new URLSearchParams(window.location.search).get(key)) !== null ||
                (this.testLocalStorage && (value = localStorage.getItem(key)) !== null)
            ) {
                return value;
            } else return defaultVal;
        },
        getPreferenceNumber(key, defaultVal) {
            var value;
            if (
                (value = new URLSearchParams(window.location.search).get(key)) !== null ||
                (this.testLocalStorage && (value = localStorage.getItem(key)) !== null)
            ) {
                return Number(value);
            } else return defaultVal;
        },
        apiUrl() {
            return this.getPreferenceString("instance", "https://pipedapi.kavin.rocks");
        },
        authApiUrl() {
            if (this.getPreferenceBoolean("authInstance", false)) {
                return this.getPreferenceString("auth_instance_url", this.apiUrl());
            } else return this.apiUrl();
        },
        getAuthToken() {
            return this.getPreferenceString("authToken" + this.hashCode(this.authApiUrl()));
        },
        hashCode(s) {
            return s.split("").reduce(function (a, b) {
                a = (a << 5) - a + b.charCodeAt(0);
                return a & a;
            }, 0);
        },
        timeAgo(time) {
            return timeAgo.format(time);
        },
        urlify(string) {
            if (!string) return "";
            const urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
            const emailRegex = /([\w-\\.]+@(?:[\w-]+\.)+[\w-]{2,4})/g;
            return string
                .replace(urlRegex, url => {
                    if (url.endsWith("</a>")) return url;
                    return `<a href="${url}" target="_blank">${url}</a>`;
                })
                .replace(emailRegex, email => {
                    return `<a href="mailto:${email}">${email}</a>`;
                });
        },
        async updateWatched(videos) {
            if (window.db) {
                var tx = window.db.transaction("watch_history", "readonly");
                var store = tx.objectStore("watch_history");
                videos.map(async video => {
                    var request = store.get(video.url.substr(-11));
                    request.onsuccess = function (event) {
                        if (event.target.result) {
                            video.watched = true;
                        }
                    };
                });
            }
        },
        getLocalSubscriptions() {
            return JSON.parse(localStorage.getItem("localSubscriptions"));
        },
        isSubscribedLocally(channelId) {
            const localSubscriptions = this.getLocalSubscriptions();
            if (localSubscriptions == null) return false;
            return localSubscriptions.includes(channelId);
        },
        handleLocalSubscriptions(channelId) {
            var localSubscriptions = this.getLocalSubscriptions() ?? [];
            if (localSubscriptions.includes(channelId))
                localSubscriptions.splice(localSubscriptions.indexOf(channelId));
            else localSubscriptions.push(channelId);
            // Sort for better cache hits
            localSubscriptions.sort();
            localStorage.setItem("localSubscriptions", JSON.stringify(localSubscriptions));
        },
        getUnauthenticatedChannels() {
            const localSubscriptions = this.getLocalSubscriptions() ?? [];
            return localSubscriptions.join(",");
        },
        /* generate a temporary file and ask the user to download it */
        download(text, filename, type) {
            var file = new Blob([text], { type: type });

            const elem = document.createElement("a");

            elem.href = URL.createObjectURL(file);
            elem.download = filename;
            elem.click();
            elem.remove();
        },
    },
    computed: {
        theme() {
            return this.getPreferenceString("theme", "dark");
        },
        authenticated(_this) {
            return _this.getAuthToken() !== undefined;
        },
        testLocalStorage() {
            try {
                if (window.localStorage !== undefined) localStorage;
                return true;
            } catch {
                return false;
            }
        },
        async defaultLangage() {
            const languages = window.navigator.languages;
            for (let i = 0; i < languages.length; i++) {
                try {
                    await import("./locales/" + languages[i] + ".json");
                    return languages[i];
                } catch {
                    continue;
                }
            }
            return "en";
        },
    },
    data() {
        return {
            TimeAgo: TimeAgo,
            TimeAgoConfig: timeAgo,
        };
    },
};

const i18n = createI18n({
    globalInjection: true,
    legacy: false,
    locale: "en",
    fallbackLocale: "en",
    messages: {
        en: enLocale,
    },
});

window.i18n = i18n;

const app = createApp(App);
app.use(i18n);
app.use(router);
app.mixin(mixin);
app.component("FontAwesomeIcon", FontAwesomeIcon);
app.mount("#app");
