import TableController from "./table/table-controller";
import {getUrlVars} from './util';
import LineController from './line/line-controller';
import EditController from './edit/edit-controller';

enum ControllerID {
    TABLE = '',
    LINE = 'view',
    EDIT = 'edit'
}

interface Routes {
    [name: string]: any
}

const createUrlParams = (params: any): string => {
    let result = ``;

    for (const key in params) {
        const val = params[key];
        result += `${key}=${val}&`;
    }
    result = result.substring(0, result.length - 1);

    return result;
};

const changeUrlParams = (data: object): void => {
    const params: object = {};
    (<any>Object).assign(params, getUrlVars(), data);
    location.hash = createUrlParams(params);
};

class App {
    constructor() {
        this.init();
    }

    private routes: Routes = {
        [ControllerID.TABLE]: new TableController(),
        [ControllerID.LINE]: new LineController(),
        [ControllerID.EDIT]: new EditController()
    };

    public showTable(data: {
        readonly pagination?: number,
        readonly search?: string
    }): void {
        changeUrlParams({
            route: ControllerID.TABLE,
            pagination: data.pagination,
            search: data.search
        });
    }

    public showLine(data: {
        id: number
    }): void {
        changeUrlParams({
            lineId: data.id,
            route: ControllerID.LINE
        });
    }

    public showEdit(data: {
        id: number
    }): void {
        changeUrlParams({
            lineId: data.id,
            route: ControllerID.EDIT
        });
    }

    private changeController(): void {
        const data: any = getUrlVars();
        const route: ControllerID = data[`route`] || ControllerID.TABLE;
        this.routes[route].init(data);
    }

    private init(): void {
        this.changeController();
        window.addEventListener(`hashchange`, () => {
            this.changeController();
        });
    }
}

export default new App();