var app=require("app"),path=require("path"),fs=require("fs"),semver=require("semver"),mkdirp=require("mkdirp"),packageName="app.asar",pendingName="pending.asar",dataPath=path.resolve(app.getPath("appData"),app.getName(),"Custom"),pendingPath=path.resolve(dataPath,pendingName),dialog=require("dialog"),BrowserWindow=require("browser-window"),net=require("net"),os=require("os"),request=require("request"),crypto=require("crypto"),noop=function(){},ProgressDialog=require("./progress_dialog"),ensureSingleInstance=function(a){"use strict";"function"!=typeof a&&(a=noop);var b;b="win32"===process.platform?"\\\\.\\pipe\\"+app.getName()+"-sock":path.resolve(os.tmpDir(),""+app.getName()+"-"+process.env.USER+".sock");var c,d,e=function(){c&&(c.close(),console.log("file socket server closed.")),fs.existsSync(b)&&(console.log("cleanup: "+b),fs.unlinkSync(b))},f=function(){console.log("first run."),c=net.createServer(function(a){a.on("data",function(a){"show"===a.toString()&&BrowserWindow.mainWindow&&BrowserWindow.mainWindow.show()})}),c.listen(b),app.on("will-quit",function(){e()}),app.on("will-exit",function(){e()}),a(!0)},g=function(){console.log("already running."),d.write("show"),d.end(),d.on("close",function(){app.quit()}),a(!1)};fs.existsSync(b)?(d=net.connect(b),d.on("error",function(a){console.error(a),e(),f()}),d.on("connect",function(){g()})):f()},download=function(a,b,c){"use strict";"function"!=typeof c&&(c=noop);var d,e=request.get(a).on("response",function(a){var f,g=parseInt(a.headers["content-length"],10),h=0,i=new Buffer(g),j=200===a.statusCode?null:new Error(a.statusMessage),k=!1;b&&(d=new ProgressDialog(b),d.on("cancel",function(){e.abort(),k=!0})),a.on("data",function(a){a.copy(i,h,0,a.length),h+=a.length,f=(h/g*100).toFixed(2)+"%	",console.log(f+h+"/"+g),d&&(d.progress=h/g*100)}),a.on("end",function(){return k?void c(new Error("Cancelled"),null):(console.log("finish.\n"),d&&d.close(!0),void c(j,i))})}).on("error",function(a){d&&d.close(!0),c(a,null)})},showNoUpdate=function(){"use strict";dialog.showMessageBox({title:"没有可用更新",message:"当前已是最新版本",buttons:["好的"]})},showUpdateError=function(a){"use strict";dialog.showMessageBox({title:"更新出错",message:"更新出错，请稍候再试",detail:a.toString(),buttons:["好的"]})},downloadManifest=function(a){"use strict";var b=require("./package.json");download(b.manifestUrl,null,function(b,c){if(b)return void a(b,c);if("function"==typeof a){var d=c.toString("utf8",0,c.length),e=null,f=null;try{e=JSON.parse(d)}catch(g){f=g}finally{a(f,e)}}})},getMd5=function(a){"use strict";var b=crypto.createHash("md5");return b.update(a),b.digest("hex")},doUpdate=function(a){"use strict";if("incremental"!==a.updateType)return void require("shell").openExternal(a.downloadUrl);var b=require("original-fs"),c="正在下载 "+a.name+" "+a.version;download(a.appUrl,c,function(c,d){if(c)return console.error(c),void showUpdateError(c);var e=getMd5(d);if(e!==a.hash){var f="different hash: \n[remote]"+a.hash+"\n[local]"+e,g=new Error(f);return console.error(g),void showUpdateError(g)}b.writeFile(pendingPath,d,{encoding:null},function(a){return a?void console.error(a):void dialog.showMessageBox({title:"更新完毕",message:"重启应用后更新生效",buttons:["好的"]})})})},checkForUpdate=function(a,b){"use strict";a&&console.log("local: "+a.version),downloadManifest(function(c,d){if(c)return console.error(c),void(b||showNoUpdate());console.log("remote: "+d.version);var e=!a||semver.gt(d.version,a.version);if(e){var f=dialog.showMessageBox({title:"发现新版本",message:d.name+" "+d.version+" 做了以下改进：",detail:d.changelog,buttons:["现在更新","以后再说"]});0===f&&doUpdate(d)}else b||showNoUpdate()})},getAppInfo=function(){"use strict";var a,b,c,d,e=path.resolve(dataPath,packageName),f=path.resolve(__dirname,packageName),g=fs.existsSync(e),h=fs.existsSync(f);return g||h?g?h?(b=require(path.resolve(e,"package.json")),c=require(path.resolve(f,"package.json")),semver.gte(b.version,c.version)?(a=e,d=b):(a=f,d=c)):(a=e,d=require(path.resolve(a,"package.json"))):(a=f,d=require(path.resolve(a,"package.json"))):(a=null,d=null),{path:a,manifest:d?d:null}},installPendingUpdate=function(){"use strict";var a=path.resolve(dataPath,packageName),b=require("original-fs");return b.existsSync(pendingPath)?(b.renameSync(pendingPath,a),!0):!1};installPendingUpdate(),app.on("ready",function(){"use strict";ensureSingleInstance(function(a){a&&mkdirp(dataPath,function(a){if(a)return console.error(a),void app.quit();var b=getAppInfo();if(checkForUpdate(b.manifest,!0),app.checkForUpdate=function(){checkForUpdate(b.manifest,!1)},b.manifest&&b.path){console.log("starting: "+b.manifest.version);var c=path.resolve(b.path,b.manifest.main);require(c)()}})})});