using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Data;
using VBNET = Microsoft.VisualBasic;
using gmRTL.Core;
using Microsoft.VisualBasic.CompilerServices;
using System.Linq;
using System.Collections.Generic;

namespace ScanToolUI
{
   public static class modScanToolUI
   {
      private const string MOD_NAME = "ScanToolUI";
      private static string logFile = "";
      public enum EShellShowConstants
      {
         essSW_HIDE = 0,
         essSW_MAXIMIZE = 3,
         essSW_MINIMIZE = 6,
         essSW_SHOWMAXIMIZED = 3,
         essSW_SHOWMINIMIZED = 2,
         essSW_SHOWNORMAL = 1,
         essSW_SHOWNOACTIVATE = 4,
         essSW_SHOWNA = 8,
         essSW_SHOWMINNOACTIVE = 7,
         essSW_SHOWDEFAULT = 10,
         essSW_RESTORE = 9,
         essSW_SHOW = 5
      }
      private const int ERROR_FILE_NOT_FOUND = 2;
      private const int ERROR_PATH_NOT_FOUND = 3;
      private const int ERROR_BAD_FORMAT = 11;
      private const int SE_ERR_ACCESSDENIED = 5;     //  access denied
      private const int SE_ERR_ASSOCINCOMPLETE = 27;
      private const int SE_ERR_DDEBUSY = 30;
      private const int SE_ERR_DDEFAIL = 29;
      private const int SE_ERR_DDETIMEOUT = 28;
      private const int SE_ERR_DLLNOTFOUND = 32;
      private const int SE_ERR_FNF = 2;     //  file not found
      private const int SE_ERR_NOASSOC = 31;
      private const int SE_ERR_PNF = 3;     //  path not found
      private const int SE_ERR_OOM = 8;     //  out of memory
      private const int SE_ERR_SHARE = 26;
      [DllImport("shell32.dll",EntryPoint="ShellExecuteA")]
      private static extern int ShellExecute(int hWnd,string lpOperation,string lpFile,string lpParameters,string lpDirectory,int nShowCmd);
      [DllImport("shell32.dll",EntryPoint="ShellExecuteA")]
      private static extern int ShellExecuteForExplore(int hWnd,string lpOperation,string lpFile,string lpParameters,string lpDirectory,int nShowCmd);
      [STAThread]
      public static void Main(string[] args)
      {
         const string FUNC_NAME = "Main";
         try
         {
            gmRTL.Core.GlobalException.Clear();

            string arg = "";
            arg = gmRTL.Core.InteractionHelper.Command();
            //  to test batch mode
            //  args = "/optRpt=DirList /Root=c:\promis\demo\_demo  /Log=c:\temp\scantool.tdf /FileFilter=*.xml"

            if (arg.Len() > 0)
            {
               runCommand(arg);
            }
            else
            {
               frmScantool frm = null;
               frm = new frmScantool();
               frm.Text = gmRTL.Core.App.DefInstance.Title + " " + gmRTL.Core.App.DefInstance.Path;
               System.Windows.Forms.Application.Run(frm);
            }

         }
         catch(System.Exception exc)
         {
            gmRTL.Core.GlobalException.Initialize(exc);
         }

         if (gmRTL.Core.GlobalException.Instance.Number != 0)
         {
            System.Windows.Forms.MessageBox.Show(MOD_NAME + "::" + FUNC_NAME + " " + gmRTL.Core.GlobalException.Instance.Description, "", MessageBoxButtons.OK);
         }
      }
      public static void runCommand(string args_migname)
      {
         const string FUNC_NAME = "runCommand";
         string rpt = "";
         ScanToolLib.clsScanControl scanControl = null;
         try
         {
            gmRTL.Core.GlobalException.Clear();


            logFile = getArg("/log=",gmRTL.Core.InteractionHelper.Command(),"scantool.tab");

            writeLog("[BGN] **************************************** " + DateTime.Now.ToStr());

            scanControl = new ScanToolLib.clsScanControl();

            string configFile = "";
            configFile = getArg("/Config=",args_migname,"");

            if (configFile.Len() > 0)
            {
               scanControl.loadScantoolConfig(configFile);
            }
            else
            {
               scanControl.txtRootPath = getArg("/Root=",args_migname,".");
               scanControl.optRpt = getArg("/OptRpt=",args_migname,"DirList");
               scanControl.txtFilFilter = getArg("/FileFilter=",args_migname,"*");
               scanControl.txtFolderFilter = getArg("/FolderFilter=",args_migname,"*");
               scanControl.txtSaveTo = scanControl.optRpt + ".tab";
            }

            scanControl.setFileProcessor();
            scanControl.runReport();


         }
         catch(System.Exception exc)
         {
            gmRTL.Core.GlobalException.Initialize(exc);
         }

         if (gmRTL.Core.GlobalException.Instance.Number != 0)
         {
            rpt = "ERRORS: " + MOD_NAME + "::" + FUNC_NAME + " " + gmRTL.Core.GlobalException.Instance.Description;
         }

         rpt = scanControl.Show() + rpt;

         writeLog(rpt + "[END] **************************************** " + DateTime.Now.ToStr());

         scanControl = null;

      }
      public static void writeLog(string rpt)
      {
         const string FUNC_NAME = "writeLog";
         System.IO.StreamWriter txt = null;
         try
         {
            gmRTL.Core.GlobalException.Clear();


            txt = (new System.IO.FileInfo(logFile)).AppendText();
            System.Diagnostics.Debug.WriteLine(rpt);
            txt.WriteLine(rpt);

         }
         catch(System.Exception exc)
         {
            gmRTL.Core.GlobalException.Initialize(exc);
         }

         txt.Close();

         txt = null;

      }
      private static string getArg(string arg,string cml,string defVal)
      {
         string getArg = "";

         const string FUNC_NAME = "getArg";
         try
         {
            gmRTL.Core.GlobalException.Clear();

            getArg = defVal;

            int iStartThisToken = 0;
            iStartThisToken = cml.InStr(arg,1,StringComparison.CurrentCultureIgnoreCase);
            if (iStartThisToken > 0)
            {
               int iStartNextToken = 0;
               iStartNextToken = cml.InStr(" /",iStartThisToken + arg.Len(),StringComparison.CurrentCulture);
               if (iStartNextToken == 0)
               {
                  iStartNextToken = cml.Len() + 1;
               }
               getArg = cml.Mid((iStartThisToken + arg.Len()), iStartNextToken - (iStartThisToken + arg.Len()));
               getArg = (getArg.ReplaceStr("\"","",1,-1,StringComparison.CurrentCulture)).TrimB();
            }
            System.Diagnostics.Debug.WriteLine(arg + "[" + getArg + "]");

         }
         catch(System.Exception exc)
         {
            gmRTL.Core.GlobalException.Initialize(exc);
         }

         if (gmRTL.Core.GlobalException.Instance.Number != 0)
         {
            gmRTL.Core.ErrorHandling.RaiseGlobalException(17,String.Empty,MOD_NAME + "::" + FUNC_NAME + " COMMAND LINE PARSINF ERROR: USAGE " + gmRTL.Core.App.DefInstance.EXEName + " {/Config=file.xml /Root=x /OptRpt=x} /log=ErrLog");
         }
         return getArg;
      }
      public static bool ShellEx(string sFIle,EShellShowConstants eShowCmd = EShellShowConstants.essSW_SHOWDEFAULT,string sParameters = "",string sDefaultDir = "",string sOperation = "open",int Owner = 0)
      {
         bool ShellEx = false;


         int lR = 0;
         int lErr = 0;
         string sErr = "";

         if (sFIle.UCase().InStr(".EXE",1,StringComparison.CurrentCulture) != 0)
         {
            eShowCmd = EShellShowConstants.essSW_HIDE;
         }
         gmRTL.Core.ErrorHandling.ResumeNext(() =>
         {
            if (sParameters == "" && sDefaultDir == "")
            {
               lR = ShellExecuteForExplore(Owner,sOperation,sFIle,"","",EShellShowConstants.essSW_SHOWNORMAL.ToInt());
            }
            else
            {
               lR = ShellExecute(Owner,sOperation,sFIle,sParameters,sDefaultDir,eShowCmd.ToInt());
            }
            if (lR < 0 || lR > 32)
            {
               ShellEx = true;
            }
            else
            {
               //  raise an appropriate error:
               ShellEx = false;
               lErr = gmRTL.Core.Constants.vbObjectError + 1048 + lR;
               switch(lR)
               {
               case 0:
                  lErr = 7;
                  sErr = "Out of memory";
                  break;
               case ERROR_FILE_NOT_FOUND:
                  lErr = 53;
                  sErr = "File not found";
                  break;
               case ERROR_PATH_NOT_FOUND:
                  lErr = 76;
                  sErr = "Path not found";
                  break;
               case ERROR_BAD_FORMAT:
                  sErr = "The executable file is invalid or corrupt";
                  break;
               case SE_ERR_ACCESSDENIED:
                  lErr = 75;
                  sErr = "Path/file access error";
                  break;
               case SE_ERR_ASSOCINCOMPLETE:
                  sErr = "This file type does not have a valid file association.";
                  break;
               case SE_ERR_DDEBUSY:
                  lErr = 285;
                  sErr = "The file could not be opened because the target application is busy. Please try again in a moment.";
                  break;
               case SE_ERR_DDEFAIL:
                  lErr = 285;
                  sErr = "The file could not be opened because the DDE transaction failed. Please try again in a moment.";
                  break;
               case SE_ERR_DDETIMEOUT:
                  lErr = 286;
                  sErr = "The file could not be opened due to time out. Please try again in a moment.";
                  break;
               case SE_ERR_DLLNOTFOUND:
                  lErr = 48;
                  sErr = "The specified dynamic-link library was not found.";
                  break;
               case SE_ERR_NOASSOC:
                  sErr = "No application is associated with this file type.";
                  break;
               case SE_ERR_OOM:
                  lErr = 7;
                  sErr = "Out of memory";
                  break;
               case SE_ERR_SHARE:
                  lErr = 75;
                  sErr = "A sharing violation occurred.";
                  break;
               default:
                  sErr = "An error occurred occurred while trying to" + sOperation + " the selected file.";
                  break;
               }

               gmRTL.Core.ErrorHandling.RaiseGlobalException(lErr,String.Empty,gmRTL.Core.App.DefInstance.EXEName + "ShellEx " + sErr);
            }

         });
         return ShellEx;
      }
   }
}
