class AppWindow{
    ID;
    Title;
    Window;
    WindowElement;
    TaskbarApp;
    DesktopApp;
    constructor(IdIn, Source, Title, X, Y) {
        this.Title = Title;
        this.ID = IdIn;
        this.DesktopApp = Source.cloneNode(true);
        this.GenerateTaskBarApp()
        if(Source.classList.contains("Fullscreen"))this.GenerateWindow(this,true);
        else this.GenerateWindow(this,false);
        //setTimeout(this.InitWin(this), 1000)
        var checkExist = setInterval( function(Element){
            //console.log("Interval")
            if (document.getElementById(Element.ID)){
                clearInterval(checkExist);
                Element.WindowElement = document.getElementById(Element.ID);
                Element.InitWin(Element, X, Y);
            }
        }, 100,this);
    }
    InitWin (element, X, Y){
        //console.log(element.WindowElement);
        element.init(element, X, Y);
        element.DragWindow(element.WindowElement, element.TaskbarApp);
        //WinManager.CalibrateWindows();
        element.DesktopApp = null;
    }
    GenerateTaskBarApp(){
        this.TaskbarApp = this.DesktopApp.cloneNode(true);
        this.TaskbarApp.classList.replace("windowIcon","windowApp")
        this.TaskbarApp.id = ("App" + this.ID);
        this.TaskbarApp.setAttribute("onClick", "");
        taskbar.appendChild(this.TaskbarApp);
    }

    GenerateWindow(self, FullscreenAble){
        var NewAppBody = new XMLHttpRequest();
        NewAppBody.open('GET', Page + "Apps/" + self.Title + '.html', true);
        NewAppBody.onreadystatechange = function () {
            if (NewAppBody.readyState !== 4) return;
            if (NewAppBody.status !== 200) return;
            self.WindowContent = NewAppBody.responseText;
            var NewAppLoaded = new XMLHttpRequest();
            if(FullscreenAble) NewAppLoaded.open('GET', "AppAssets/AppFullscreen.html", true);
            else NewAppLoaded.open('GET', "AppAssets/App.html", true);
            NewAppLoaded.onreadystatechange = function () {
                if (NewAppLoaded.readyState !== 4) return;
                if (NewAppLoaded.status !== 200) return;
                self.Window = NewAppLoaded.responseText;
                self.Window = self.Window.replaceAll("{id}", "" + self.ID);
                self.Window = self.Window.replace("{x}", self.DesktopApp.classList[3]);
                self.Window = self.Window.replace("{y}", self.DesktopApp.classList[4]);
                self.Window = self.Window.replace("{ApplicationName}", self.Title + "Name");
                self.Window = self.Window.replace("Application", self.Title.replace(/([A-Z])/g, ' $1').trim());
                self.Window = self.Window.replace("{WindowIconImage}", self.DesktopApp.children[0].src);
                self.Window = self.Window.replace("{body}", self.WindowContent);
                if(FullscreenAble){
                    var URL = self.WindowContent.split('src="')[1];
                    var newURL = URL.split('"')[0];
                    self.Window = self.Window.replace("{FullScreenLocation}", newURL + (!newURL.includes("http") ? "?fullscreen=true&desktop=true" : "?from=halbearnet"));
                }
                document.getElementById("AppContainer").insertAdjacentHTML("beforeend",self.Window);
            };
            NewAppLoaded.send();
        }
        NewAppBody.send();
    }

    init(element, X, Y) {
        element.WindowElement.style.width = element.WindowElement.classList[1] + "vh";
        element.WindowElement.style.height = element.WindowElement.classList[2] + "vh";
        element.WindowElement.style.left = (X-(((element.WindowElement.offsetWidth/2)/innerWidth)*100)) + "vw";
        element.WindowElement.style.top = (Y-(((element.WindowElement.offsetHeight/2)/innerHeight)*100)) + "vh";
        element.WindowElement.classList.remove("minimised")
    }

    DragWindow(Window, WindowTaskBarApp){
        if (Window.classList.contains(".Initialised")) AppInit(Window);

        var Touchscreen = false;
        var CalculatedLeft = 0, CalculatedTop = 0, OldLeft = 0, OldTop = 0;
        Window.children[0].addEventListener('mousedown', mouseDown);
        Window.children[0].addEventListener('touchstart', mouseDown);
        WindowTaskBarApp.addEventListener('mousedown', AppMinimise)
        WindowTaskBarApp.addEventListener('touchstart', AppMinimise)
        document.getElementById(Window.id + "ExitBtn").addEventListener('mousedown', ExitApp);
        document.getElementById(Window.id + "MinimiseBtn").addEventListener('mousedown', AppMinimise);
        document.getElementById(Window.id + "ExitBtn").addEventListener('touchstart', ExitApp);
        document.getElementById(Window.id + "MinimiseBtn").addEventListener('touchstart', AppMinimise);

        function mouseDown(mouse) {
            console.log("mouseDown");
            Touchscreen = mouse.type === "touchstart";
            mouse.preventDefault();
            if (!Window.classList.contains('DraggingActive')){
                Window.style.zIndex = ""+55;
                if (Touchscreen) {
                    document.addEventListener('touchmove', mouseMove);
                    document.addEventListener('touchend', mouseUp);
                } else {
                    document.addEventListener('mousemove', mouseMove);
                    document.addEventListener('mouseup', mouseUp);
                }
                Window.classList.add('DraggingActive');
                Window.children[1].classList.add("Dragging");
                OldLeft = mouse.clientX;
                OldTop = mouse.clientY;
                Window.children[1].style.transition = '0.5s';
                setTimeout(function(){
                    Window.children[1].style.transition = '0.0s';
                }, 500);
            }
        }
        function mouseMove(mouse){
            mouse.preventDefault();
            if (!Touchscreen) {
                CalculatedLeft = OldLeft - mouse.clientX;
                CalculatedTop = OldTop - mouse.clientY;
                OldLeft = mouse.clientX;
                OldTop = mouse.clientY;
                Window.style.top = clamp(((Window.offsetTop - CalculatedTop)/innerHeight)*100,0,(((innerHeight - Window.offsetHeight)/innerHeight)*100)- 5) + 'vh';
                Window.style.left =clamp(((Window.offsetLeft - CalculatedLeft)/innerWidth)*100,0,(((innerWidth - Window.offsetWidth)/innerWidth)*100)- 0.5) + 'vw';
            } else {
                Window.style.top = clamp((mouse.changedTouches[0].clientY/innerHeight)*100,0,(((innerHeight - Window.offsetHeight)/innerHeight)*100)- 5) + 'vh';
                Window.style.left = clamp((mouse.changedTouches[0].clientX/innerWidth)*100,0,(((innerWidth - Window.offsetWidth)/innerWidth)*100) - 0.5) + 'vw';
            }
        }
        function mouseUp(mouse){
            Window.children[1].classList.remove('Dragging');
            //Window.removeEventListener('mousedown', mouseDown);
            //Window.removeEventListener('touchstart', mouseDown);
            Window.classList.remove('DraggingActive');
            if (Touchscreen){
                document.removeEventListener('touchmove', mouseMove);
                document.removeEventListener('touchend', mouseUp);
                Touchscreen = false;
            }
            else {
                document.removeEventListener('mousemove', mouseMove);
                document.removeEventListener('mouseup', mouseUp);
            }
            Window.children[1].style.transition = '0.5s';
            Window.style.zIndex = ""+50;
            setTimeout(function(){
                Window.children[1].style.transition = '0.0s';
            }, 500);
        }

        function AppMinimise(mouse){

            if (Window.classList.contains("minimised")) {
                Window.classList.add("animationTransition");
                Window.classList.remove("minimised");
                setTimeout(()=>{
                    Window.classList.remove("animationTransition");
                },500)
            } else {
                Window.classList.add("minimised");
            }
        }

        function ExitApp(mouse) {
            var TaskbarApp = document.getElementById("App" + Window.id);
            TaskbarApp.remove();
            Window.remove();
        }
    }
}
class WindowManager{
    Windows = [];
    constructor(){
        this.Windows = [];
    }
    NewWindow(IdIn, Source, Title, X, Y){
        let newWindow = new AppWindow(IdIn, Source, Title, X, Y);
        this.Windows.push(newWindow);
        return newWindow;
    }

    CalibrateWindows(){
        for (let i = 0; i < this.Windows.length; i++){
            this.Windows[i].DragWindow(this.Windows[i].WindowElement, this.Windows[i].TaskbarApp);
        }
    }

    get WindowCount(){
        return this.Windows.length;
    }
}

let WinManager = new WindowManager();
var SelectedApp;
var AppIdCounter = 0;
var click = false;
const taskbar = document.getElementById("taskbar");

//console.log(WinManager.WindowCount);
function clamp(number, lower, upper) {
    if (number > upper) {
        return upper;
    }
    if (number < lower) {
        return lower;
    }
    return number;
}

function OpenApp(Source, skip, X, Y){
    if (SelectedApp !== Source && !skip){
        if (SelectedApp != null){
            SelectedApp.classList.remove("selectedIcon");
        }
        SelectedApp = Source;
        Source.classList.add("selectedIcon");
    } else{
        SelectedApp = null;
        Source.classList.remove("selectedIcon");
        let Title = Source.children[1].innerHTML;
        WinManager.NewWindow(AppIdCounter, Source, Title, X, Y);
        AppIdCounter++;

    }
}