const http=require("http"),urltool=require("url"),pfs=require("pfs"),putil=require("./p-util"),querystring=require("querystring"),fs=require("fs"),PieServer=function(){let e=process.cwd(),t="index.html",r=new Map,i=new Map,a={Server:"PieServer","access-control-allow-origin":"*"};Object.defineProperties(this,{rootdir:{set:t=>{e=t},get:()=>e},indexName:{set:e=>{t=e},get:()=>t},dirMap:{get:()=>r},connector:{get:()=>i},headData:{get:()=>a}});let s=this.mimeMap=new Map([[".bmp","image/bmp"],[".png","image/png"],[".gif","image/gif"],[".jpg","image/jpeg"],[".svg","image/svg+xml"],[".html","text/html"],[".htm","text/html"],[".js","application/javascript"],[".css","text/css"],[".appcache","text/cache-manifest"],[".json","application/json"],[".map","application/octet-stream"]]);(this.server=http.createServer()).on("request",async(n,o)=>{let p=urltool.parse(n.url),{pathname:c}=p,l=0,g=/\/(.+?)\//.exec(n.url);if(g){g=g[1];let e=r.get(g);e&&(c=c.replace("/"+g,e),l=1)}l||(/\/$/.test(c)&&(c+=t),c=e+c,c=decodeURIComponent(c));let h,d=n.headers,m=Object.assign({},a),u=/(.+)(\..+)$/g.exec(c.toLowerCase());if((u=u&&u[2])&&(h=s.get(u))&&(m["Content-Type"]=h),h&&h.search("image")>-1)try{let e=await pfs.stat(c);m["Content-Length"]=e.size,o.writeHead(200,m),fs.createReadStream(c).pipe(o)}catch(e){o.writeHead(404),o.end("error : no file")}else{let e,t,r=0;switch(n.method){case"POST":t=await putil.getPostData(n);break;case"GET":t=querystring.parse(p.query)}for(let a of i)if(p.pathname==a[0]){e=await a[1]({data:t,request:n}),r=1;break}try{r||(e=await pfs.readFile(c));let t=d["accept-encoding"];t&&t.search("gzip")>-1&&(e=await putil.gzip(e),m["Content-Encoding"]="gzip"),m["Content-Length"]=e.length,o.writeHead(200,m),o.end(e)}catch(e){o.writeHead(404),o.end("error : no data"),console.warn("no file => ",c)}}})};PieServer.prototype={listen(e){this.server.listen(e)},on(){this.server.on.apply(this.server,arguments)},close(){this.server.close()}},Object.defineProperties(PieServer.prototype,{port:{get:function(){return this.server.address().port}}}),module.exports=PieServer;