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

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

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

    render() {
        return this.generatedTemplate;
    }

    setRoute({ attributes = {}, state = {} } = {}, { view } = {}) {
        getTemplate(view).then(tmpl => {
            this.generatedTemplate = tmpl.html;
            this.routeParams = { ...state, ...attributes };
            this.attributes = tmpl.attributes(this);
        });
    }

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