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 FMStocks_DB
{
   public static class Helpers
   {
      // TransactionType enum
      public enum FMStocks_TransactionType
      {
         Pending_Buy = 1,
         Pending_Sell = 2,
         Bought = 3,
         Sold = 4,
         Insufficient_Funds = 5,
         Not_Enough_Shares = 6
      }
      // Debug String Messages
      public const string cstrStarting_Method = "Starting Method call";
      public const string cstrFinishing_Method = "Finishing Method call";
      public const string cstrError_Method = "Error in Method call";
      // WIN32 API Functions used to write to EventLog and get the Computername
      [DllImport("advapi32.dll",EntryPoint="RegisterEventSourceA")]
      public static extern int RegisterEventSource(string lpUNCServerName,string lpSourceName);
      [DllImport("advapi32.dll")]
      public static extern int DeregisterEventSource(int hEventLog);
      [DllImport("advapi32.dll",EntryPoint="ReportEventA")]
      [return : System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
      public static extern bool ReportEvent(int hEventLog,int wType,int wCategory,int dwEventID,object lpUserSid,int wNumStrings,int dwDataSize,ref int plpStrings,object lpRawData);
      [DllImport("kernel32")]
      public static extern int GetLastError();
      [DllImport("kernel32",EntryPoint="RtlMoveMemory")]
      public static extern void CopyMemory(object hpvDest,object hpvSource,int cbCopy);
      [DllImport("kernel32")]
      public static extern int GlobalAlloc(int wFlags,int dwBytes);
      [DllImport("kernel32")]
      public static extern int GlobalFree(int hMem);
      [DllImport("kernel32",EntryPoint="GetComputerNameA")]
      private static extern int GetComputerNameAPI(string lpBuffer,ref int nSize);
      public static void LogNTEvent(string sString,int iLogType,int iEventID,string sEventTitle) // UPGRADE_INFO: hand-coded
      {
         gmRTL.Core.App.DefInstance.LogEvent(sString, (System.Diagnostics.EventLogEntryType)iLogType,iEventID, sEventTitle);
      }
      //  mp is short for MakeParameter - does typesafe array creation for use with Run* functions
      public static object[] mp(string PName,System.Data.SqlDbType PType,int PSize,object PValue)
      {
         return new object[]{PName,PType,PSize,PValue};
      }
      // Converts a variant into a string. If the varaint is null, it is converted to the empty string.
      public static string ConvertToString(object v)
      {
         string ConvertToString = "";

         if (Convert.IsDBNull(v))
         {
            ConvertToString = "";
         }
         else
         {
            ConvertToString = v.ToStr();
         }
         return ConvertToString;
      }
      // Converts any Null variant to null, otherwise it returns the existing value.
      public static decimal NullsToZero(object v) // UPGRADE_INFO: hand-coded
      {
         decimal NullsToZero = 0.00M;
         var f = v as gmRTL.DataLib.SqlClient.Field;
         if (f != null)
         {
            var value = f.Value;
            NullsToZero = (value == DBNull.Value ? 0 : Convert.ToDecimal(value));
         }
         else
         {
            NullsToZero = (v == null ? 0 : Convert.ToDecimal(v));
         }
         return NullsToZero;
      }
      // Raise an error without changing the transaction state.
      public static void RaiseError(string module,string functionName,string strErrDesc,int lngErrNum,bool bWriteToLog)
      {
         // log the error to the event for later use.
         string strSource = "";

         if (strErrDesc == "")
         {
            strErrDesc = gmRTL.Core.GlobalException.Instance.Description;
         }
         if (lngErrNum == 0)
         {
            lngErrNum = gmRTL.Core.GlobalException.Instance.Number;
         }

         strSource = CreateSourceStack(module,functionName);

         // add custom logging here... for now we log to application event log
         if (bWriteToLog)
         {
            logError(lngErrNum,strSource,strErrDesc,"");
         }

         gmRTL.Core.ErrorHandling.RaiseGlobalException(lngErrNum,strSource,strErrDesc);
      }
      public static string GetComputerName() // UPGRADE_INFO: hand-coded
      {
         return System.Environment.MachineName;
      }
      private static string CreateSourceStack(string objectName,string procName)
      {
         //  Returns an source stack like message like:  "[FMStocks_DB.Account] VerifyUser [on AHI version 5.21.176]"
         //  add tab to each line in the  new source stack

         return (gmRTL.Core.GlobalException.Instance.Source + "\r\n" + "[" + objectName + "]  " + procName + " [" + GetComputerName() + " version " + GetVersionNumber() + "]").ReplaceStr("\r\n",("\t" + "\r\n"),1,-1,StringComparison.CurrentCulture);
      }
      // returns the current DLL version number
      public static string GetVersionNumber()
      {
         return gmRTL.Core.App.DefInstance.Major.ToStr() + "." + gmRTL.Core.App.DefInstance.Minor + "." + gmRTL.Core.App.DefInstance.Revision;
      }
      // function takes a string with an '=' in it and returns the left part
      // GetKey("test=1") return test
      public static string GetKey(string strItem)
      {
         string GetKey = "";

         int i = 0;

         i = strItem.InStr("=",1,StringComparison.CurrentCultureIgnoreCase);
         if (i > 0)
         {
            GetKey = strItem.Left((i - 1));
         }
         else
         {
            GetKey = "";
         }
         return GetKey;
      }
      // function takes a string with an '=' in it and returns the right part
      // GetValue("test=1") return 1
      public static string GetValue(string strItem)
      {
         string GetValue = "";

         int i = 0;

         i = strItem.InStr("=",1,StringComparison.CurrentCultureIgnoreCase);
         if (i > 0)
         {
            GetValue = strItem.Mid((1 + i));
         }
         else
         {
            GetValue = "";
         }
         return GetValue;
      }
      // this procedure logs an error to the system application log
      private static void logError(int errnum,string source,string description,string notes)
      {

         gmRTL.Core.App.DefInstance.LogEvent("\r\n" + "An error has occured in an FMStocks 2000 component." + "\r\n" + "Error Number:" + errnum + "\r\n" + "\r\n" + "Source: " + "\r\n" + source + "\r\n" + "\r\n" + "Description:" + "\r\n" + description + "\r\n" + "\r\n" + "Notes: " + "\r\n" + notes,System.Diagnostics.EventLogEntryType.Error);     //  FMC1: App.LogEvent Optional Parameter

      }
      // this procedure logs an error to the system application log
      private static void logEvent(string source,string description,string notes)
      {

         gmRTL.Core.App.DefInstance.LogEvent("\r\n" + "FMStocks 2000 Debug event." + "\r\n" + "Source: " + "\r\n" + source + "\r\n" + "\r\n" + "Description:" + "\r\n" + description + "\r\n" + "\r\n" + "Notes: " + "\r\n" + notes,System.Diagnostics.EventLogEntryType.Error);     //  FMC1: App.LogEvent Optional Parameter

      }
      public static void logDebugMSG(bool bWriteMSG,string strEvent,string strSource,string strMSG)
      {

         if (bWriteMSG)
         {
            logEvent(strEvent + " -- " + strSource,"Debug event from " + strSource,strMSG);
         }

      }
   }
}
