const{deleteResource:deleteResource,createDir:createDir,writeFile:writeFile,readFile:readFile,getPagesDirPath:getPagesDirPath,getLayoutsDirPath:getLayoutsDirPath}=require("./wm-utils"),{getPagesConfig:getPagesConfig}=require("./project-meta"),util=require("util"),cheerio=require("cheerio"),{safeString:safeString}=require("./handlebar-helpers"),{formatMarkup:formatMarkup}=require("./wm-utils"),path=require("path"),ncp=util.promisify(require("ncp").ncp),createIntermediateAppSkeleton=async(e,t)=>{await deleteResource(t),await createDir(t,{recursive:!0}),await ncp(e,t,{filter:t=>!path.relative(e,t).startsWith("target")})},generateLayoutsAndPages=async e=>{const t=getLayoutsDirPath(e);await createDir(t,{recursive:!0});const a=await getPagesConfig(e),r=getPagesDirPath(e),n=[],i=[];for(let e of a)if("PAGE"===e.type){const a=await readFile(`${r}/${e.name}/${e.name}.html`,"utf8"),o=cheerio.load(a),l=o("wm-page"),s=o("wm-page-content");["wm-alertdialog","wm-confirmdialog","wm-dialog","wm-iframedialog","wm-pagedialog","wm-logindialog"].forEach(e=>{const t=o(e);t.length&&s.append(t)});const u=await getLayoutMarkup(o,l,s,n);u.markup&&(n.push({name:u.name,layoutInfo:u.layoutInfo}),i.push({name:u.name,type:"LAYOUT"}),await createDir(`${t}/${u.name}`,{recursive:!0}),await writeFile(`${t}/${u.name}/${u.name}.html`,u.markup)),e.layout=u.name,s.attr("spa","true"),s.attr("columnwidth","12"),s.attr(l.attr()),s.attr("layout",u.name);const g=formatMarkup(safeString(s.toString()).string);await writeFile(`${r}/${e.name}/${e.name}.html`,g)}await writeFile(`${r}/pages-config.json`,JSON.stringify(a,null,4)),await writeFile(`${t}/layouts-config.json`,JSON.stringify(i,null,4))},getLayoutMarkup=async(e,t,a,r)=>{const n=getLayoutInfo(e);let i=getLayoutName(n,r);if(i)return{name:i};{const o=r.length+1;i=`layout_${o}`,n.leftNav&&e("wm-left-panel").attr("spa","true");const l=e("<wm-router-outlet>");l.attr("columnwidth",a.attr().columnwidth),e("wm-page-content").replaceWith(l);const s=e("<wm-layout>");return s.attr("name",`layout${o}`),s.append(t.children()),{name:i,markup:formatMarkup(safeString(s.toString()).string),layoutInfo:n}}},getLayoutInfo=e=>{const t={header:e("wm-header"),topNav:e("wm-top-nav"),leftNav:e("wm-left-panel"),rightNav:e("wm-right-panel"),footer:e("wm-footer")},a={};for(const e in t)if(t.hasOwnProperty(e)&&t[e].length){const r=t[e].attr().content,n=r&&r.startsWith("bind:"),i=t[e].children().length;a[e]={content:r,hasBindExpr:n,hasChildren:i}}return a},getLayoutName=(e,t)=>{for(const a of t)if(Object.keys(a.layoutInfo).sort().join(",")===Object.keys(e).sort().join(",")){if(Object.keys(e).every(t=>e[t].content===a.layoutInfo[t].content&&!(e[t].hasBindExpr||a.layoutInfo[t].hasBindExpr||e[t].hasChildren||a.layoutInfo[t].hasChildren)))return a.name}};module.exports={createIntermediateAppSkeleton:createIntermediateAppSkeleton,generateLayoutsAndPages:generateLayoutsAndPages};