/**메뉴의 생성과 선택 시 동작을 지원한다.
 */
class FimsMenuSupport extends MenuSupport {

	constructor(selector) {
		super(selector);

		this._menuItem = '<li data-key="{menuID}" class="menu-item">'
			+'<a data-url="{url}" onclick="openMenu(this)" class="menu-link{toggle}">'
				+'<i class="menu-icon tf-icons {imageConf}"></i>'
				+'<div data-i18n="{menuName}">{menuName}</div>'
			+'</a>'
			+'{menuSub}'
		+'</li>';
	}

	setMenuInfo(menus) {
		
		let setParent = menu => {
			let children = menu.children || [];
			if (children.length < 1) return;
			
			children.forEach(child => {
				child.parent = menu;
				setParent(child);
			});
		};
		menus.forEach(menu => setParent(menu));
		this._menus = menus;
		
		let menuItemTag = menu => {
			let tag = this._menuItem
				.replace(/{menuID}/gi, menu.id)
				.replace(/{menuName}/gi, menu.name)
				.replace(/{url}/gi, !menu.url ? "javascript:void(0);" : wctx.url(menu.url))
				.replace(/{imageConf}/gi, !menu.imageConf ? "bx bx-layout" : menu.imageConf);
			let parent = menu.children && menu.children.length > 0;
			tag = tag.replace(/{toggle}/gi, !parent ? "" : " menu-toggle");
			if (!parent)
				return tag.replace(/{menuSub}/gi, "");
			
			let children = menu.children.map(child => menuItemTag(child)).join("\n\t")
			return tag.replace(/{menuSub}/gi, this._menuSub.replace(/{children}/gi, children));
		}
		let tags = (menus || []).map(menu => menuItemTag(menu));
		document.querySelector("#menus").innerHTML = tags.join("");
		
		return this._init();
	}
	
}


/**************************************************************************
 * Global Variable
 ***************************************************************************/
const innerPageMap = {},
      openMax = 8;

function openMenu(obj, params) {

	let menuUrl = $(obj)[0].dataset.url;
	if(menuUrl == "javascript:void(0);"){
		return;
	}

	let menuNm = $(obj).find("div")[0].dataset.i18n;

	let dataKey = $(obj).parent()[0].dataset.key;



    const OPEN_TAB_CNT = $('div#tabsForInnerPage > ul > li').length;

    if(innerPageMap[dataKey]){
        // 해당 tab 활성화
        $("#tabsForInnerPage").find("ul li button.nav-link").each((idx, data) => {
            if(data.dataset.bsTarget == ("#tab-"+dataKey)) {
                $(data).trigger("click");
            }
        });
        return;
    }

    if(OPEN_TAB_CNT === openMax){
        alert(`메뉴는 최대 ${openMax -1}까지만 열 수 있습니다.`)
        return null;
    }


    let liEl = '<li id="li-'+ dataKey +'" class="nav-item">';
    let linkClass = 'nav-link';
    if(dataKey != "dashboard"){
        linkClass += ' nav-link-closeable';
    }
    liEl +='<button type="button" data-bs-toggle="tab" data-bs-target="#tab-'+ dataKey + '" class="' + linkClass + '">' + menuNm + '</button>';
    if(dataKey != "dashboard"){
        liEl += '<button type="button" title="닫기" class="btn btn-close" onclick="closeTab('+ dataKey + ')"></button>'
    }
    liEl += '</li>';
    $('div#tabsForInnerPage ul').append(liEl);

    $('div#innerPageTabContents').append('<div id="tab-' + dataKey + '" class="tab-pane"></div>');


    if(params != null){
        menuUrl = menuUrl + params;
    }

	let dynamicPage = document.createElement("div");
	dynamicPage.setAttribute("id","innerPage-"+dataKey);

       // .attr("frameborder"  , "0")
       // .attr("scrolling"    , "no")
      //  .attr("width"        , "100%")
      //  .css("border"        , "0")
     //   .css("height"        , "100%")
     //   .css("min-height"    , "800px")
     //   .css("overflow"      , "auto")
     //   .css("overflow-x"    , "no")
    ;

	$("#formForInnerPage").remove();


	$("#tab-" + dataKey)[0].appendChild(dynamicPage);


    innerPageMap[dataKey] = dynamicPage;


	ajax.request({
		type:"POST",
		url:menuUrl,
		data:{},
		success:resp => {
			$("#innerPage-"+dataKey).html(resp);
		}
	});



	$("div#tabsForInnerPage ul li button.nav-link").last().trigger("click");

}

function closeTab(menuId) {
    if(menuId === 'main' || menuId?.id === 'main')   return;
    const num_tabs = $('div#tabsForInnerPage ul li').length;

    // click한 tab
    const selIdx = id2Index("div#tabsForInnerPage","tab-"+menuId);

    // active tab
    let activeTab = $('div#tabsForInnerPage ul li button.nav-link').filter(".active");

    let activeIdx = $('div#tabsForInnerPage ul li button.nav-link').index(activeTab);

    if(selIdx === activeIdx) {
        if (num_tabs - 1 > activeIdx) {
            $('div#tabsForInnerPage ul li button.nav-link').eq(activeIdx + 1).trigger("click");
        } else {
            $('div#tabsForInnerPage ul li button.nav-link').eq(activeIdx - 1).trigger("click");
        }
    }

    document.getElementById("innerPage-"+menuId).remove();
    delete innerPageMap[menuId];

    $("#tab-" + activeIdx).remove();
    $('#tabsForInnerPage').find('#li-'+menuId).remove();
}

function id2Index(tabsId, srcId) {
    let index = -1;
    const nls = $(tabsId).find("li > button.nav-link");
    if(nls.length > 0) {

        nls.each((idx, nl) => {
            if (nl.dataset.bsTarget.search(srcId) > 0) {
                index = idx;
                return false;
            }
        });
    }
    return index;
}