const iPms=require("./initData"),launcherUtil=require("./launcherUtil"),PieServer=require("pieServer"),path=require("path"),pfs=require("pfs"),util=require("util");let copydir=require("copy-dir");copydir=util.promisify(copydir);let{app:app,ipcMain:ipcMain,BrowserWindow:BrowserWindow}=require("electron");module.exports=(async()=>{const{listen:e,apps:r,serverDir:t}=await iPms;var a=new PieServer;a.rootdir=t+"/",r.forEach(e=>{switch(e.type){case"sapp":a.dirMap.set(e.name,t+`/${e.name}/app/`)}}),a.listen(e);let i={pageCreator:new Map};ipcMain.on("d-msg",async(a,n)=>{let{sender:s}=a,{type:o}=n;switch(o){case"getList":let a={};for(let e in i){let r=i[e],t=a[e]=[];r.forEach(e=>{t.push({dirpath:e.dirpath,stat:e.stat})})}s.send("notice-initList",a);break;case"getData":s.send("notice-initData",{listen:e,apps:r,serverDir:t})}}),ipcMain.on("c-msg",async(e,r)=>{let s,{sender:o}=e,{type:p,dirpath:d,appName:l}=r;switch(l&&(s=((e,r)=>{let t=i[r]||(i[r]=new Map),a=t.get(e);return a||(a={appName:r,dirpath:e,stat:0},t.set(e,a)),a})(d,l)),p){case"getList":let e={};for(let r in i){let t=i[r],a=e[r]=[];t.forEach(e=>{a.push({dirpath:e.dirpath,stat:e.stat})})}o.send("notice-launcher",{stat:"initList",sData:e,serverDir:t});break;case"new":(c=await launcherUtil.create({appName:l,dirpath:d})).stat?o.send("notice-launcher",{stat:"add",dirpath:d}):o.send("notice-launcher",{stat:"adderror",dirpath:d,error:c.error});break;case"open":var c;Object.assign(s,{openSender:o,stat:"loading"}),(c=await launcherUtil.open({appName:l,dirpath:d})).stat||o.send("notice-launcher",{stat:"error",dirpath:d,error:c.error});break;case"running":var{mapping:h,fileUpload:u}=r;if(s.stat="running",h){for(let e in h)a.dirMap.set(e,h[e]);s.mapping=h}if(u){for(let e in u)(e=>{let r=u[e];a.connector.set("/"+e,async e=>{let{data:t}=e,a="img_"+(new Date).getTime()+path.extname(t.name),i=r+"/"+a;return await pfs.writeFile(i,t.file),JSON.stringify({stat:1,name:a,desc:"upload ok"})})})(e);s.fileUpload=u}!n&&s.openSender.send("notice-launcher",{stat:"ok",dirpath:s.dirpath,port:(901217*r.port).toString(32),data:r}),s.serverSender=o;break;case"openError":!n&&s.openSender.send("notice-launcher",{stat:"error",dirpath:s.dirpath,error:r.error,data:r}),i[l].delete(d),console.error(r.error);break;case"close":s.serverSender.send("to-closePageServer"),!n&&s.openSender.send("notice-launcher",{stat:"close",dirpath:s.dirpath,data:r}),delete s.openSender,delete s.serverSender,i[l].delete(d);var{mapping:h,fileUpload:u}=s;if(h)for(let e in h)a.dirMap.delete(e);if(u)for(let e in u)a.connector.delete(e)}console.log("server收到了信号",r)});let n=0,s=new BrowserWindow({width:960,height:720,backgroundColor:"#303336",frame:!1,titleBarStyle:"hiddenInset",resizable:!1,maximizable:!1,webPreferences:{nodeIntegration:!0}});s.on("closed",e=>{n=1,app.quit()}),s.loadFile(`${t}/c_launcher/index.html`)});