// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8303#8303
// Description(1033): Opens files located in the folder
// Description(1049): Открывает файлы, находящиеся в папке
// Version: 1.5 (2015.01.15)
// Author: VladSh
// 
// Arguments:
// 	-file - initial file
// 	-binary:
// 		• [""]    - behavior by default
// 		• "1warn" - one question about binary
// 		• "ignoreAll" - ignore all binaries
// 		• "openAll" - silent opening all binaries
// 		
// Usage:
// 	-"Открыть все файлы папки" Call("Scripts::Main", 1, "OpenAllFilesFromFileFolder.js", `-file="%f" -binary="1warn"`) Icon("%a\AkelFiles\Plugs\Coder.dll", 1)

var hWndMain = AkelPad.GetMainWnd();
var pFileCurrent = AkelPad.GetEditFile(0);
var path = AkelPad.GetArgValue("file", pFileCurrent);
var binary = AkelPad.GetArgValue("binary", "");
var openBinary = null;

if (! AkelPad.Include("ProcessFolderFiles.js")) WScript.Quit();
//if (typeof(processFolderFiles) == "function")		//Проверка, подключена ли функция, т.к. подключаемого скрипта может не быть на диске (оставил для памяти)
processFolderFiles(path, true);


function processFile(file) {
	if (file == pFileCurrent) return;
	
	if (!binary) {	//behavior by default
		AkelPad.OpenFile(file);
	}
	else {
		if (!isFileBinary(file)) {
			AkelPad.OpenFile(file, 0x002 /* OD_ADT_REG_CODEPAGE */);	//opening nonbinary
		}
		else {
			if (binary == "ignoreAll") {
				return;
			}
			else if (binary == "1warn") {
				if (openBinary == null) {
					openBinary = AkelPad.OpenFile(file, 0x001 /* OD_ADT_BINARY_ERROR */);	//opening binary with question
					return;
				}
				else if (openBinary == -22 /* EOD_MSGCANCELBINARY */) {	//skip
					return;
				}
			}
			//в т.ч. binary == "openAll"
			AkelPad.OpenFile(file, 0x002 /* OD_ADT_REG_CODEPAGE */);	//silent opening binary WITH codepage detecting
//			AkelPad.OpenFile(file, 0);	//silent opening binary WITHOUT codepage detecting
		}
	}
}

/* Instructor's code (http://akelpad.sourceforge.net/forum/viewtopic.php?p=11344#11344) */
function isFileBinary(pFile) {
	var lpDetectCodepage;
	var bResult = false;

	if (lpDetectCodepage = AkelPad.MemAlloc(_X64?24:20 /*sizeof(DETECTCODEPAGEW)*/)) {
		AkelPad.MemCopy(lpDetectCodepage /*offsetof(DETECTCODEPAGEW, pFile)*/, AkelPad.MemStrPtr(pFile), 2 /*DT_QWORD*/);
		AkelPad.MemCopy(lpDetectCodepage + (_X64?8:4) /*offsetof(DETECTCODEPAGEW, dwBytesToCheck)*/, 1024, 3 /*DT_DWORD*/);
		AkelPad.MemCopy(lpDetectCodepage + (_X64?12:8) /*offsetof(DETECTCODEPAGEW, dwFlags)*/, 0x11 /*ADT_BINARY_ERROR|ADT_NOMESSAGES*/, 3 /*DT_DWORD*/);
		if (AkelPad.SendMessage(hWndMain, 1177 /*AKD_DETECTCODEPAGEW*/, 0, lpDetectCodepage) == -4 /*EDT_BINARY*/)
			bResult = true;

		AkelPad.MemFree(lpDetectCodepage);
	}
	return bResult;
}