// http://akelpad.sourceforge.net/forum/viewtopic.php?p=27098#27098
// Version: 1.3
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Show sessions menu for open.
// Description(1049): Показать меню сессий для открытия.
//
// Arguments:
// -ForceNewInstance=true   -Open session in new instance (required script ForceNewInstance.js). Default is false.
//
// Usage:
// Call("Scripts::Main", 1, "SessionsOpenMenu.js", `-ForceNewInstance=true`)

//Include
if (!AkelPad.Include("ShowMenu.js")) WScript.Quit();

//Arguments
var bForceNewInstance=AkelPad.GetArgValue("ForceNewInstance", false);

//Variables
var fso=new ActiveXObject("Scripting.FileSystemObject");
var hMainWnd=AkelPad.GetMainWnd();
var oSys=AkelPad.SystemFunction();
var oFolder;
var oFiles;
var aFiles=[];
var aItems=[];
var nItem=0;
var pSessionsDir=GetSessionsDir();

if (pSessionsDir)
{
  //Find files
  oFolder=fso.GetFolder(pSessionsDir);

  for (oFiles=new Enumerator(oFolder.files); !oFiles.atEnd(); oFiles.moveNext())
  {
    if (fso.GetExtensionName(oFiles.item().Name).toLowerCase() == "session")
      aFiles.push(fso.GetBaseName(oFiles.item().Name));
  }

  if (aFiles.length)
  {
    //Sort array
    aFiles=aFiles.sort(function(a, b)
    {
      return oSys.Call("kernel32::lstrcmpi" + _TCHAR, a, b);
    });

    //Show menu
    for (; nItem < aFiles.length; ++nItem)
      aItems[nItem]=[aFiles[nItem], MF_NORMAL, nItem];

    if ((nItem=ShowMenu(aItems, POS_CURSOR, POS_CURSOR)) != -1)
    {
      if (bForceNewInstance)
        AkelPad.Call("Scripts::Main", 1, "ForceNewInstance.js", '-CmdLine=`/Call("Sessions::Main", 1, "' + aItems[nItem][0] + '")`');
      else
        AkelPad.Call("Sessions::Main", 1, aItems[nItem][0]);
    }
  }
}

function GetSessionsDir()
{
  var oSys=AkelPad.SystemFunction();
  var oSet=AkelPad.ScriptSettings();
  var nSaveSessions=1 /*SDIR_PROGRAM*/;
  var lpBuffer;
  var pSessionsDir="";

  if (oSet.Begin("Sessions", 0x21 /*POB_READ|POB_PLUGS*/))
  {
    nSaveSessions=oSet.Read("SaveSessions", 1 /*PO_DWORD*/);
    oSet.End();
  }
  if (nSaveSessions == 1 /*SDIR_PROGRAM*/)
    pSessionsDir=AkelPad.GetAkelDir(4 /*ADTYPE_PLUGS*/) + "\\Sessions";
  else if (nSaveSessions == 2 /*SDIR_APPDATA*/)
  {
    if (lpBuffer=AkelPad.MemAlloc(256 * _TSIZE))
    {
      oSys.Call("shell32::SHGetSpecialFolderPath" + _TCHAR, hMainWnd, lpBuffer, 0x1a /*CSIDL_APPDATA*/, 0);
      pSessionsDir=AkelPad.MemRead(lpBuffer, _TSTR) + "\\AkelPad\\Sessions";
      AkelPad.MemFree(lpBuffer);
    }
  }
  return pSessionsDir;
}
