import { IArmisaPageKey } from "../ArmisaImportPage";
import { MainStateManager } from "../MainStateManager";
import { INaming } from "../NamingCaption";
import { PageFactory } from "./PageFactory";

export class PageTabingFactory {
    public tabs: PageFactory[];
    public tabsOrder: PageFactory[];
    public activeTab?: PageFactory;

    constructor(
        public mainStateManager: MainStateManager,
        public forceUpdate: () => void,
        public lazyLoadPage: (pageKey: IArmisaPageKey) => React.LazyExoticComponent<React.ComponentType<any>>
    ) {
        this.tabs = [];
        this.tabsOrder = [];
    }

    addNewTab = (pageKey: IArmisaPageKey, caption: INaming | string) => {
        let captionFinal = '';
        if (caption) {
            if (typeof caption === 'string') {
                captionFinal = caption;
            } else if (caption) {
                captionFinal = this.mainStateManager.getCaptionNaming(caption);
            }
        }

        const newTab = new PageFactory(this, pageKey, captionFinal, this.lazyLoadPage);
        this.tabs.push(newTab);
        this.tabsOrder.push(newTab);
        this.activeTab = newTab;
        this.forceUpdate();
    }

    selectThisTab = (tab: PageFactory) => {
        const newTabOrder = this.tabsOrder.filter((t) => t !== tab);
        newTabOrder.push(tab);
        this.tabsOrder = newTabOrder;
        // this.mainStateManager.focusPosition = 'tabs';
        this.forceUpdate();
    }

    closeThisTab = (tab: PageFactory) => {
        this.tabs = this.tabs.filter((t) => t !== tab);
        this.tabsOrder = this.tabsOrder.filter((t) => t !== tab);

        if (this.tabsOrder.length > 0) {
            this.activeTab = this.tabsOrder[this.tabsOrder.length - 1];
        } else {
            this.activeTab = undefined;
        }

        if (this.tabs.length === 0) {
            // this.mainStateManager.focusPosition = 'filterMenu';
            // this.mainStateManager.setFocus();
        }
        this.forceUpdate();
    }

    public mensuringWidthSize = () => {
        this.forceUpdate();
    }

    public startHelpMode = () => {
        this.forceUpdate();
    }
}