import { UIInternal } from "./ui-internal";
import { Router } from 'aurelia-router';

export function changeRoutesNav(router: Router, changeRouteModels: ChangeRouteNav | ChangeRouteNav[]) {
    let changes = (Array.isArray(changeRouteModels) ? changeRouteModels : [changeRouteModels]);
    if (changes.some(x => null == (x.href || x.name || x.route))) {
        console.warn("One or more route changes have no href/name/route");
    }
    let anyChanged = changes.reduce((anyChanged, changeRouteModel) => changeRouteNav(router, changeRouteModel) || anyChanged, false);
    if (anyChanged) {
        UIInternal.broadcast(UIInternal.EVT_ROUTE_CHANGE);
    }
}

function changeRouteNav(router: Router, changeRouteModel: ChangeRouteNav): boolean {
    let i = router.routes.findIndex(x =>
        (changeRouteModel.href != null && x.href == changeRouteModel.href)
        || (changeRouteModel.name != null && x.name == changeRouteModel.name)
        || (changeRouteModel.route != null && x.route == changeRouteModel.route));
    if (i >= 0) {
        router.routes[i].nav = changeRouteModel.nav;
        return true;
    }
    return false;
}

export interface ChangeRouteNav {
    href?: string;
    name?: string;
    route?: string;
    nav: boolean;
}