import fonts.fontAwesome;
import ide;
import fsys;
import zlib.httpFile;
import inet.http;

var publisDir = ide.getPublisDir();
if(!#publisDir)return; 

var projectDir = ide.getProjectDir();
var electronAppDir = ..io.joinpath(projectDir,"/electron.app") ;
if( !..io.exist(electronAppDir) ) {
	if( ..io.exist(..io.joinpath(projectDir,"\package.json")) ){
		electronAppDir = projectDir;
	}
}

if( !..io.exist(electronAppDir) ) {
    return;
}

import fonts.fontAwesome;
import win.ui;
/*DSG{{*/
var winform = win.form(text="aardio - 正在构建asar文件列表( 关闭窗口跳过这一步 )";right=1075;bottom=734;acceptfiles=1;exmode="none";mode="popup";parent=...)
winform.add(
btnOpen={cls="button";text='\uF019  添加';left=25;top=8;right=129;bottom=43;disabled=1;dl=1;dt=1;font=LOGFONT(name='FontAwesome');z=4};
btnPack={cls="plus";text='\uF0AE  生成asar文件';left=863;top=668;right=1038;bottom=697;bgcolor=-6960024;font=LOGFONT(name='FontAwesome';charset=0);notify=1;z=11};
btnRemove={cls="button";text='\uF093  移除';left=135;top=8;right=239;bottom=43;disabled=1;dl=1;dt=1;font=LOGFONT(name='FontAwesome');z=9};
btnReset={cls="button";text='\uF112  重置';left=272;top=8;right=355;bottom=43;disabled=1;dl=1;dt=1;font=LOGFONT(name='FontAwesome');z=7};
chePortable={cls="checkbox";text="生成的asar文件嵌入到exe文件";left=752;top=637;right=1016;bottom=661;checked=1;db=1;dr=1;z=8};
editInfo={cls="richedit";left=371;top=8;right=1064;bottom=628;db=1;dl=1;dr=1;dt=1;edge=1;hscroll=1;multiline=1;vscroll=1;z=2};
editOutPath={cls="edit";left=136;top=668;right=840;bottom=697;db=1;dl=1;dr=1;edge=1;z=5};
progress={cls="progress";left=21;top=710;right=1058;bottom=723;db=1;dl=1;dr=1;edge=1;hide=1;max=100;min=0;z=3};
static={cls="static";text="输出文件";left=42;top=672;right=128;bottom=696;align="right";db=1;dl=1;transparent=1;z=6};
static2={cls="static";text="如果工程中不存在/electron.app 目录, 此窗口不会显示";left=72;top=635;right=496;bottom=659;color=16711680;db=1;dl=1;transparent=1;z=10};
treeview={cls="treeview";left=18;top=51;right=364;bottom=628;bgcolor=16777215;db=1;dl=1;dt=1;edge=1;vscroll=1;z=1}
)
/*}}*/

winform.btnPack.skin({
	background={
		active=0xFF252E45;
		default=0xFF68CC95;
		disabled=0xFFC4CCC8;
		hover=0xFF4A522F
	};
	color={
		active=0xFFFFFFFF;
		default=0xFF000000;
		disabled=0xFF8A8A8A;
		hover=0xFFFFFFFF
	}
})

win.setOwner(winform.hwnd,ide.getMainHwnd());

import fsys.asar.writer;
var asarFile = fsys.asar.writer();
var packageDevDependencies = {
    ["electron"]=true;
	["accessibility-developer-tools"]=true;
	["electron-winstaller"]=true;
	["electron-chromedriver"]=true;
	["electron-download"]=true;
	["electron-packager"]=true;
	["eslint"]=true;
	["tslint"]=true;
	["jest"]=true;
	["@types"]=true;
	["yarn"]=true;
};

var packagePath = ..io.joinpath(electronAppDir,"\package.json")
if(..io.exist(packagePath)){
    import web.json;
	var packageInfo = web.json.parse(packagePath);
	if(packageInfo[["devDependencies"]]){
		..table.assign(packageDevDependencies,packageInfo[["devDependencies"]]);
	}
}

var winformDestroyed
winform.onDestroy = function(){
    winformDestroyed = true;
}
 
import string.glob; 
var ignoreGlob = string.glob({".aardio-ignore";".git";".gitignore";
	".gitattributes";"**.aproj";"**.aardio";"**.exe"});
ignoreGlob.load( ..io.joinpath(electronAppDir,".aardio-ignore") )
 
var match = string.match;
var find = string.find;
var peekPumpMessage = win.peekPumpMessage;
var toRelativePath = fsys.path.relative;
asarFile.filter = function(path){
    if(peekPumpMessage()===null || winformDestroyed ) return false;
    var relativePath = toRelativePath(path,electronAppDir,false);
    if(ignoreGlob.test(relativePath)){
    	return false;
    } 
	  
    var module = match(relativePath,"node_modules\\([^\\]+)$") 
    if(module){ 
    	return !packageDevDependencies[module];
    }
    return true;
}

var showAsarInfo = function(){
	var treeData,err = asarFile.treeData(); 
	if(!treeData){
		winform.msgboxErr(err)
		return;	
	}
	winform.treeview.clear();
	winform.treeview.insertItem(treeData); 

	if( ( !# ( ..string.trim( winform.editOutPath.text )) )
		|| (winform.editOutPath.autoPath = winform.editOutPath.text ) ){
		winform.editOutPath.text = fsys.path.removeBackslash(asarFile.rootDirectory) + ".asar";
		winform.editOutPath.autoPath = winform.editOutPath.text;
	}
}

winform.btnReset.oncommand = function(id,event){
	asarFile.clear(); 
	winform.editInfo.text = "";
	winform.btnRemove.disabled = true;
	
	winform.btnOpen.disabled = true;
	winform.btnReset.disabled = true;
	winform.btnPack.disabled = true;
	winform.btnReset.disabledText = {'\uF254';'\uF251';'\uF252';'\uF253';'\uF250'}
	winform.btnRemove.disabled = true;
	
	asarFile.add( electronAppDir  )
	showAsarInfo();
	
	winform.btnReset.disabledText = null
	winform.btnPack.disabled = false;
	winform.btnOpen.disabled = false;
	winform.btnReset.disabled = false;	
}

import fsys.dlg;
winform.btnOpen.oncommand = function(id,event){
	var path = fsys.dlg.open("*.*|*.*||","添加文件到asar文件",,winform.hwnd);
	if(#path){
		asarFile.add( path );
		showAsarInfo();
	} 
}

winform.wndproc = {
    [0x233/*_WM_DROPFILES*/] = function(hwnd,message,wParam,lParam){ 
		var files = win.getDropFile(wParam);
		if(#files){
			for(i=1;#files;1){
				asarFile.add( files[i] );
			}
			
			showAsarInfo();
		};
	}
}

import fsys;
import win.ui.menu;
import process;
winform.treeview.onnotify = function(id,code,ptr){
 
    if( code == 0xFFFFFE3D/*_TVN_SELCHANGEDW*/ ){  
		var hItem = winform.treeview.getSelection();
		if(hItem){
			winform.btnRemove.disabled = false;
			
			var data  = winform.treeview.getItemData(hItem);
			var data = table.clone(data); 
			for(k,v in data){
				if( v[["size"]] ) v.size =..math.size64(v.size).format(); 
			}
			if( data[["size"]] ) data.size =..math.size64(data.size).format(); 
			
            winform.editInfo.text = web.json.stringify(data,true)
		}
		else {
			winform.btnRemove.disabled = true;
		}
    } 
}

import fsys.dlg;
winform.btnPack.oncommand = function(id,event){
	var outpath = winform.editOutPath.text;
	if(!#outpath){
		outpath = fsys.dlg.save("*.asar|*.asar||","请选择asar文件",,winform.hwnd);
	} 
	
	if(!#outpath) return;
	if(!..string.endWith(outpath,".asar",true)){
		winform.msgboxErr("输出文件必须以.asar作为文件名后缀");
		winform.editOutPath.setFocus();
		return;
	}
	
	io.remove(outpath);
	if(io.exist(outpath)){
		winform.msgboxErr('文件被占用中:\n' + outpath)
		return;
	}
	
	winform.btnOpen.disabled = true;
	winform.btnReset.disabled = true;
	winform.progress.hide = false;
	winform.btnPack.text = '\uF0AE  构建中...'
	winform.btnPack.disabledText = {'\uF254';'\uF251';'\uF252';'\uF253';'\uF250'}
    winform.progress.setRange(1,1000);
    for(path,size,progress in asarFile.eachPack(outpath)){
    	winform.progress.pos = progress * 1000;
    	
		win.peekPumpMessage();	
		if(winformDestroyed) return;
    } 
	 
	if( asarFile.lasterr ) winform.msgboxErr(asarFile.lasterr)
	else {
		if( winform.chePortable.checked ){
			var exe = ide.getPublishPath();
			var file = io.open(exe,"a+b");
			if( file ){
				var bin = ..string.loadBuffer(outpath)
				if( bin ){
					file.writeBuffer(bin);
					file.write({
						INT size = #bin;
						BYTE magic[4] = "ASAR";
					});
					file.close();
				
					io.remove(outpath);
				}
				else {
					winform.msgboxErr("添加ASAR到EXE文件失败,ASAR文件加载失败")
				}
				
			}
			else {
				winform.msgboxErr("添加ASAR到EXE文件失败")
			}
		}	
		
		asarFile.clear();
		
		fsys.delete( ..io.joinpath(ide.getPublisDir(),"/electron.app") );;
	}
	
	winform.progress.hide = true;
	winform.btnPack.disabledText = null;
	winform.btnPack.text = '\uF0AE  生成asar文件'
	winform.btnOpen.disabled = false;
	winform.btnReset.disabled = false;
	winform.close();
}

winform.editOutPath.text = fsys.joinpath(publisDir,"/electron.app.asar" );
winform.editOutPath.disabled = true;

winform.btnRemove.oncommand = function(id,event){
	var hItem = winform.treeview.getSelection();
	if(hItem){
		var path = winform.treeview.getItemPath(hItem);
		if(asarFile.remove(path)){
			winform.treeview.delItem(hItem)
		}
	}	
}

winform.enableDpiScaling();
winform.show();

ide.showStatus("正在构建asar文件列表,如果JS文件较多可能耗时比较久,请耐心等待");
winform.btnPack.text = '\uF0AE  正在创建文件列表'
winform.btnPack.disabledText = {'\uF254';'\uF251';'\uF252';'\uF253';'\uF250'}
winform.btnRemove.disabled = true;
win.delay(10)
asarFile.add( electronAppDir  )
showAsarInfo();

winform.text = "aardio - 打包asar文件( 关闭窗口跳过这一步 )"
winform.btnPack.disabledText = null
winform.btnPack.text = '\uF0AE  生成asar文件'
winform.btnOpen.disabled = false;
winform.btnReset.disabled = false;

win.loopMessage();
return winform;
