import EventBus from '../core/EventBus.js';
import Store from '../core/Store.js';
import CacheManager from '../core/CacheManager.js';
import ApiClient from '../core/ApiClient.js';
import AuthService from '../core/AuthService.js';

import TabManager from '../core/TabManager.js';

import LoginView from '../views/LoginView.js';
//import DashboardView from '../views/DashboardView.js';


export default class App {

    constructor(config) {

        this.config = config;

        // Core
        this.eventBus = new EventBus();
        this.store = new Store(this.eventBus);
        this.cache = new CacheManager();

        // API + Auth
        this.api = new ApiClient({
            config,
            eventBus: this.eventBus,
            store: this.store,
            cache: this.cache
        });

        this.auth = new AuthService({
            api: this.api,
            store: this.store,
            eventBus: this.eventBus
        });

        // Tabs
        this.tabManager = new TabManager({
            eventBus: this.eventBus,
            store: this.store,
            api: this.api,
            cache: this.cache,
            auth: this.auth
        });

        this.currentView = null;
    }

    /* ---------------------------------------------------------
       INIT
    --------------------------------------------------------- */

    async init() {

        await this.tabManager.init();

        // Check if user is already logged in
        const loggedIn = await this.auth.checkSession();

        if (loggedIn) {
            this.openDashboard();
        } else {
            this.openLogin();
        }

        this._listenGlobalEvents();
    }

    /* ---------------------------------------------------------
       VIEW SWITCHER
    --------------------------------------------------------- */

    _loadView(ViewClass) {

        if (this.currentView) {
            this.currentView.destroy();
        }

        const view = new ViewClass({
            eventBus: this.eventBus,
            store: this.store,
            tab: this.tabManager.getCurrentTab()
        });

        this.currentView = view;

        const container = document.querySelector(this.config.mount);

        view.render(container);
    }

    openLogin() {
        this._loadView(LoginView);
    }

    openDashboard() {
        this._loadView(DashboardView);
    }

    /* ---------------------------------------------------------
       GLOBAL EVENTS
    --------------------------------------------------------- */

    _listenGlobalEvents() {

        // Auto redirect to login if unauthorized
        this.eventBus.on('auth:unauthorized', () => {
            this.openLogin();
        });

        this.eventBus.on('auth:login_success', () => {
            this.openDashboard();
        });

        this.eventBus.on('auth:logout', () => {
            this.openLogin();
        });
    }

}
