import React from 'react';
import { observable, computed } from "mobx";
import { icons } from '../constants/icons';

import Mark from 'mark.js';
import { items } from '../constants/items';
import { categories } from '../constants/categories';

interface IUser {
    username: string,
    avatar: any,
    email: string,
    id: number
}

class Store {
    @observable
    public inputRef: HTMLInputElement = React.createRef<HTMLInputElement>();

    @observable
    public themeFlexyRef: HTMLDivElement = React.createRef<HTMLDivElement>();

    @observable
    public sidebarRef: HTMLDivElement = React.createRef<HTMLDivElement>();
    
    @observable
    public indicatorPosition: number = 10;

    @observable
    public sidebarBottomPx: number = 0;

    @observable
    public selectedCategory: string = "tab-id";

    @observable
    public isToggled: boolean = false;

    @observable
    public isSearchToggled: boolean = false;

    @observable
    public fssValue: string = '';

    @observable
    public sections: { id: string, scrollPos: number, element: HTMLElement }[] = [];

    @observable
    public settings: any = {
        theme: "light"
    };

    public mark;

    public constructor() {
        const performanceStart = Date.now();

        window.addEventListener('resize', () => {
            calculateSectionPositions()
            calculateThemeRounder()
            calculateSectionBottom()

            if(window.innerWidth >= 1601) {
                this.isToggled = false;
                this.isSearchToggled = false;

                const node: HTMLInputElement = this.inputRef.current;

                node.value = this.fssValue;
            }
        })

        window.addEventListener('keydown', (e) => {
            calculateSectionPositions()
            calculateSectionBottom()

            if(e.keyCode == 27) {
                this.isToggled = false;
            }
        })

        window.addEventListener('DOMContentLoaded', () => {
            this.mark = new Mark(document.querySelector("#mount-view"));

            calculateSectionPositions()
            calculateThemeRounder()
            calculateSectionBottom()
            console.log(`Loaded settings in ${Date.now() - performanceStart}ms`)

            this.themeFlexyRef.current.addEventListener('wheel', (e: WheelEvent) => {
                this.themeFlexyRef.current.scrollLeft -= (e.deltaY*1.5);
                e.preventDefault();
            })

            this.view.addEventListener('scroll', () => {
                calculateThemeRounder()
            })
        })

        const calculateThemeRounder = () => {
            this.themeRounderTop = this.themeFlexyRef.current.childNodes[0].getBoundingClientRect().top-0.2;
            this.themeRounderWidth = this.themeFlexyRef.current.getBoundingClientRect().width;
        }

        const calculateSectionPositions = () => {
            this.sections = []

            document.getElementById("mount-view").childNodes.forEach((node: HTMLElement) => {
                let scrollPos = node.getBoundingClientRect().top+150

                if(node.id.split("mount-")[1] == "id") scrollPos = node.getBoundingClientRect().top-125

                return this.sections.push({
                    id: node.id.split("mount-")[1],
                    scrollPos: Math.round(scrollPos),
                    element: node
                })
            });

        }

        const calculateSectionBottom = () => {
            const sidebar = (this.sidebarRef.current as HTMLDivElement);
            let children = Array.from(sidebar.children);
            children.shift();
    
            let height = 0;
    
            children.forEach((child: HTMLDivElement) => {
                height += child.getBoundingClientRect().height+4
            });
    
            if(this.sidebarRef.current.getBoundingClientRect().height >= 361) {
                this.sidebarBottomPx = this.sidebarRef.current.getBoundingClientRect().height-height;
            } else {
                this.sidebarBottomPx = 0;
            }
        }
    }

    @observable
    public session: IUser = {
        username: "Guest",
        avatar: icons.defaultAvatar,
        email: "guest@dothq.co",
        id: -1
    }

    @observable
    public themeRounderTop: number = -1;

    @observable
    public themeRounderWidth: number = 828;

    @observable
    public settingsChanged: boolean = false;

    public onInputChange = (e) => {
        const stripped = window.location.href.split("?")[0];

        if(this.inputRef.current.value.length == 0) {
            return window.history.replaceState(null, null, stripped);
        }

        this.fssValue = this.inputRef.current.value

        window.history.replaceState(null, null, `${stripped}?q=${this.inputRef.current.value}`);

        console.log(this.mark.mark)

        this.mark.unmark({
            done: function(mark) {
                mark.mark(this.inputRef.current.value, {});
          }
        });
    }

    public get view() {
        return document.getElementById("mount-view-scroller")
    }

    public get selectedView() {
        if(this.selectedCategory == "tab-id") return {
            id: "tab-id",
            name: this.session.username,
            icon: this.session.avatar
        }

        const item = document.getElementById(this.selectedCategory)

        if(!item) return {}

        let categoryItem = categories.find(i => i.name === item.innerText);
        if(!categoryItem) categoryItem = null;

        return {
            id: item.id,
            name: item.innerText,
            icon: categoryItem ? categoryItem.icon : null
        }
    }

    public settingsHandoff(onClick: () => void) {
        onClick();

        this.settingsChanged = true;
    }

}

export default new Store();