/*
Author: lujjjh
用法:   将文件拖放至窗口即可
*/

import win.ui;
import string.crypt;
/*DSG{{*/
var winform = win.form(parent=...; right=479;acceptfiles=1;bottom=343;text="AAuto Hasher";border="resizable" )
winform.add( 
richedit={ dr=1;dl=1;vscroll=1;right=472;left=8;dt=1;db=1;cls="richedit";readonly=1;bottom=256;wrap=1;multiline=1;top=25;font=LOGFONT( name="宋体";h=-12 );z=3;edge=1;text="" };
static={ bottom=21;right=336;left=13;dt=1;top=5;transparent=1;z=6;text="请从外部拖动文件到下面的文本框中:";cls="static" };
progress={ dr=1;dl=1;bottom=284;max=100;right=472;left=8;top=264;font=LOGFONT( name="宋体";h=-12 );text="progress";z=2;db=1;min=0;edge=1;cls="progress" };
chkMd5={ dl=1;checked=1;bottom=320;group=1;text="MD5";left=16;top=304;font=LOGFONT( name="宋体";h=-12 );z=4;db=1;right=96;cls="checkbox" };
groupbox={ dr=1;dl=1;bottom=328;right=472;left=8;top=288;font=LOGFONT( name="宋体";h=-12 );z=1;db=1;text="请选择类型：";edge=1;cls="groupbox" };
chkSha1={ dl=1;checked=1;bottom=320;right=184;left=104;top=304;font=LOGFONT( name="宋体";h=-12 );z=5;db=1;text="SHA1";cls="checkbox" }
)
/*}}*/

getHash = function (szPath) {
	winform.modifyStyleEx( 0x10/*_WS_EX_ACCEPTFILES*/);
	
	winform.chkMd5.disabled = true;
	winform.chkSha1.disabled = true;
	var bMD5, bSHA1 = winform.chkMd5.checked, winform.chkSha1.checked;
	
	var md5 = string.crypt.md5();
	var sha1 = string.crypt.sha1();
	
	winform.richedit.setsel(-1, -1);
	winform.richedit.selText = "正在计算..." + szPath + '\n';
	
	var f = io.open(szPath, "rb");
	if(!f)
		error("打开文件失败" + lasterr())
		
	var dwSize = f.seek("end"); 
	f.seek("set");
	
	var bufsize = 1024 * 1024
	var data = f.read(bufsize);
	
	do { 
		if (bMD5)
			md5.push(data);
		if (bSHA1)
			sha1.push(data);
		
		winform.progress.pos = f.seek() / dwSize * 100;
		win.delay(1); // 避免 CPU100% 
		
		data = f.read(bufsize); // 每次读取 1MB 数据
	} while (data);
	f.close();
	
	if (winform.chkMd5.checked) {
		winform.richedit.setsel(-1, -1);
		winform.richedit.selText = 'MD5:\t' + md5.getHash() + '\n';
	}
	if (winform.chkSha1.checked) {
		winform.richedit.setsel(-1, -1);
		winform.richedit.selText = 'SHA1:\t' + sha1.getHash() + '\n';
	}
	
	winform.richedit.setsel(-1, -1);
	winform.richedit.selText = string.repeat(40, "-") + '\n';
	
	winform.chkMd5.disabled = false;
	winform.chkSha1.disabled = false;
	winform.modifyStyleEx( ,0x10/*_WS_EX_ACCEPTFILES*/);
}

winform.wndproc = function(hwnd,message,wparam,lparam){
	select(message) {//判断消息类型
		case 0x233/*_WM_DROPFILES*/ {
			var szPath = win.getDropFile(wparam);
			for (k,v in szPath) {
				getHash(v);
			}
		}
	}
}

winform.progress.bottom = winform.progress.bottom - 8;
winform.show();
win.loopMessage();
