/**
 * Created by liangwensen on 3/14/16.
 */

import lang from 'zero-lang';
import domQuery from 'zero-dom/query';
import tg from 'toc-generator';
import hashRouter from 'zero-routing/hashRouter';

import instanceCache from './storage/instance';

let menus = {
    fulfill() {
        let tocContainer = domQuery.one('#toc');
        let instance = instanceCache.get('current');
        let links = [];

        function loadTopic(topic, sheetId, level) {
            links.push({
                level: level,
                uniqueId: sheetId + '/' + topic.id,
                text: topic.getTitle(),
            });
            level++;
            lang.each(topic.children || [], function (childTopic) {
                loadTopic(childTopic, sheetId, level);
            });
        }

        lang.each(instance.sheets, function (sheet) {
            let currentLevel = 1;
            links.push({
                level: currentLevel,
                uniqueId: sheet.id,
                text: sheet.getTitle(),
            });
            currentLevel++;
            loadTopic(sheet.rootTopic, sheet.id, currentLevel);
        });

        let toc = new tg.Toc(links);
        toc.placeAt(tocContainer);
        toc.on('clicked', function (headerMeta) {
            hashRouter('/' + headerMeta.uniqueId);
        });
    },
};

export default menus;
