import { LightningElement, track } from 'lwc';
import { subscribe } from 'talon/routingService';
import { getTemplate } from 'talon/moduleRegistry';
import { getThemeLayoutByView } from 'talon/themeService';
import defaultHtml from './app.html';

export default class App extends LightningElement {
    @track generatedTemplate = defaultHtml;
    @track attributes;
    @track routeParams = {};
    themeLayout;

    /**
     * Subscribe to route changes
     */
    connectedCallback() {
        this.subscription = subscribe(this.setRoute.bind(this));
    }

    render() {
        return this.generatedTemplate;
    }

    setRoute({ attributes = {}, state = {} } = {}, { view } = {}) {
        const params = { ...state, ...attributes };
        const themeLayout = getThemeLayoutByView(view);

        // only fetch a new template if it's necessary
        if (this.themeLayout !== themeLayout) {
            getTemplate(themeLayout).then(tmpl => {
                this.generatedTemplate = tmpl.html;
                this.themeLayout = themeLayout;
                this.routeParams = params;
                this.attributes = tmpl.attributes(this);
            });
        } else {
            // update any route params
            this.routeParams = params;
        }
    }

    disconnectedCallback() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
