// ******************************************************************************//
//  RAYTHEON PROPRIETARY: THIS DOCUMENT CONTAINS DATA OR INFORMATION
//  PROPRIETARY TO RAYTHEON COMPANY AND IS RESTRICTED TO USE ONLY BY PERSONS
//  AUTHORIZED BY RAYTHEON COMPANY IN WRITING TO USE IT. DISCLOSURE TO
//  UNAUTHORIZED PERSONS WOULD LIKELY CAUSE SUBSTANTIAL COMPETITIVE HARM TO
//  RAYTHEON COMPANY''S BUSINESS POSITION. NEITHER SAID DOCUMENT NOR ITS
//  CONTENTS SHALL BE FURNISHED OR DISCLOSED TO OR COPIED OR USED BY PERSONS
//  OUTSIDE RAYTHEON COMPANY WITHOUT THE EXPRESS WRITTEN APPROVAL OF RAYTHEON
//  COMPANY.
//
//  THIS PROPRIETARY NOTICE IS NOT APPLICABLE IF DELIVERED TO THE U.S. GOVERNMENT
//
//  UNPUBLISHED WORK - COPYRIGHT RAYTHEON COMPANY.
//
//  WARNING: THIS DOCUMENT CONTAINS TECHNICAL DATA AND / OR TECHNOLOGY WHOSE
//  EXPORT OR DISCLOSURE TO NON-U.S. PERSONS, WHEREVER LOCATED, IS RESTRICTED
//  BY THE INTERNATIONAL TRAFFIC IN ARMS REGULATIONS (ITAR) (22 C.F.R. SECTION
//  120-130) OR THE EXPORT ADMINISTRATION REGULATIONS (EAR) (15 C.F.R. SECTION
//  730-774). THIS DOCUMENT CANNOT BE EXPORTED (E.G., PROVIDED TO A SUPPLIER
//  OUTSIDE OF THE UNITED STATES) OR DISCLOSED TO A NON-U.S. PERSON, WHEREVER
//  LOCATED, UNTIL A FINAL JURISDICTION AND CLASSIFICATION DETERMINATION HAS
//  BEEN COMPLETED AND APPROVED BY RAYTHEON, AND ANY REQUIRED U.S. GOVERNMENT
//  APPROVALS HAVE BEEN OBTAINED. VIOLATIONS ARE SUBJECT TO SEVERE CRIMINAL
//  PENALTIES.
//
//  DOD 5220.22-M, INDUSTRIAL SECURITY MANUAL, CHAPTER 5, SECTION 1 THROUGH 9 :
//  FOR CLASSIFIED DOCUMENTS FOLLOW THE PROCEDURES IN OR DOD 5200.1-R,
//  INFORMATION SECURITY PROGRAM, CHAPTER 6. FOR UNCLASSIFIED, LIMITED DOCUMENTS
//  DESTROY BY ANY  METHOD THAT WILL PREVENT DISCLOSURE OF CONTENTS OR
//  RECONSTRUCTION OF THE DOCUMENT.
// ****************************************************************************//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace Raytheon.Common
{
   /// <summary>
   /// Read/Write to an ini file.
   /// </summary>
   public class IniConfigurationFile : ConfigurationFileBase
   {
      #region PrivateMemberVariables

      internal static class NativeMethods
      {
         [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
         internal static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedstring, int nSize, string lpFileName);

         [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
         [return: MarshalAs(UnmanagedType.Bool)]
         internal static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string line, string lpFileName);

         [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
         [return: MarshalAs(UnmanagedType.Bool)]
         internal static extern bool WritePrivateProfileSection(string lpAppName, string line, string lpFileName);

         [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
         internal static extern int GetPrivateProfileSectionNames(byte[] sections, int bufferSize, string filename);
      }

      #endregion

      /// <summary>
      /// The constructor. It will check to make sure the file exists and throw an exception it if does not
      /// </summary>
      /// <param name="fileName">The ini file name (path).</param>
      public IniConfigurationFile(string fileName)
         : base(fileName)
      {
         if (ConfigurationFileType != ConfigurationFileType.INI)
         {
            throw new ArgumentException("Expecting INI file configuration type");
         }

         if (!_fileInfo.Exists)
         {
            throw new Exception($"Can't find file: {fileName}");
         }
      }

      #region PublicFunctions

      /// <summary>
      /// reads a value from configuration file
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="section"></param>
      /// <param name="key"></param>
      /// <param name="defaultValue"></param>
      /// <returns></returns>
      public override T ReadValue<T>(string section, string key, T defaultValue = default)
      {
         const int BUFFER_SIZE = 1024;
         string temp = new string('\0', BUFFER_SIZE);
         int numBytes = NativeMethods.GetPrivateProfileString(section, key, "", temp, BUFFER_SIZE, _fileName);
         if (numBytes == 0)
         {
            WriteValue<T>(section, key, defaultValue);
            return defaultValue;
         }
         else
         {
            temp = temp.TrimEnd('\0');
            return TypeConverter.ChangeType<T>(temp);
         }
      }

      /// <summary>
      /// reads a value from configuration file
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="section"></param>
      /// <param name="key"></param>
      /// <param name="defaultValue"></param>
      /// <returns></returns>
      public override string ReadValue(string section, string key)
      {
         const int BUFFER_SIZE = 1024;
         string temp = new string('\0', BUFFER_SIZE);

         if (!ReadAllSections().Contains(section))
            throw new Exception($"Section '{section}' doesn't exist in {_fileName}");

         if (!ReadAllKeys(section).Contains(key))
            throw new Exception($"Key '{key}' doesn't exist under section '{section}' in {_fileName}");

         int numBytes = NativeMethods.GetPrivateProfileString(section, key, "", temp, BUFFER_SIZE, _fileName);
         if (numBytes > 0)
         {
            return temp.TrimEnd('\0');
         }
         else
         {
            throw new Exception($"The value associated with key '{key}' under section '{section}' is empty in {_fileName}");
         }
      }

      /// <summary>
      /// Write string value
      /// </summary>
      /// <param name="section"></param>
      /// <param name="key"></param>
      /// <param name="lineToWrite"></param>
      public override void WriteValue<T>(string section, string key, T lineToWrite)
      {
         if (!NativeMethods.WritePrivateProfileString(section, key, $"{lineToWrite}", _fileName))
         {
            throw new Exception($"IniFile::WriteValue() - WritePrivateProfileString returned false for section: {section}, key {key}, line {lineToWrite}");
         }
      }

      /// <summary>
      /// reads a list of values from INI configuration file
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="section"></param>
      /// <param name="key"></param>
      /// <param name="defaultList"></param>
      /// <returns></returns>
      public override List<T> ReadList<T>(string section, string key, IList<T> defaultList = null)
      {
         List<T> resultList = new();

         string stringResult = ReadValue(section, key, string.Empty);

         if (string.IsNullOrEmpty(stringResult))
         {
            WriteList(section, key, defaultList);
            return new List<T>(defaultList);
         }

         foreach (string item in stringResult.Split('|'))
         {
            resultList.Add(TypeConverter.ChangeType<T>(item));
         }

         return resultList;
      }

      /// <summary>
      /// writes a list of values to INI configuration file
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="section"></param>
      /// <param name="key"></param>
      /// <param name="listToWrite"></param>
      public override void WriteList<T>(string section, string key, IList<T> listToWrite)
      {
         List<string> stringListToWrite = new(listToWrite.Select(a => a.ToString()));
         WriteValue(section, key, string.Join("|", stringListToWrite));
      }

      /// <summary>
      /// Reads all keys from a section of an ini file.
      /// </summary>
      /// <param name="section">The section.</param>
      /// <returns>A list of all keys.</returns>
      public override List<string> ReadAllKeys(string section)
      {
         const int BUFFER_SIZE = 100000;
         string temp = new('\0', BUFFER_SIZE);
         int numBytes = NativeMethods.GetPrivateProfileString(section, null, "", temp, BUFFER_SIZE, _fileName);

         List<string> keyList = new List<string>();

         if (numBytes == 0)
         {
            return keyList;
         }

         temp = temp.TrimEnd('\0');
         keyList.AddRange(temp.Split('\0'));

         return keyList;
      }

      /// <summary>
      /// Returns a list of all of the sections in the ini file.
      /// </summary>
      /// <returns>A list of all sections.</returns>
      public override List<string> ReadAllSections()
      {
         List<string> sectionList = new();

         // allocate a 10K buffer.
         const int BUFFER_SIZE = 10240;
         // allocate a 10K buffer. Should be enough to handle plenty of power systems
         byte[] buffer = new byte[BUFFER_SIZE];
         int numBytesReturned = NativeMethods.GetPrivateProfileSectionNames(buffer, BUFFER_SIZE, _fileName);

         if (numBytesReturned == BUFFER_SIZE)
         {
            throw new Exception("IniFile::ReadAllSections() - returned the max buffer size. Probably have more items in config file than we can handle");
         }
         else if (numBytesReturned == 0)
         {
            return sectionList;
         }

         // convert the buffer to a string
         string result = System.Text.Encoding.Unicode.GetString(buffer);
         // trim the end of the string
         result = result.TrimEnd('\0');
         // split the string
         string[] sectionListTemp = result.Split('\0');
         // ass the sections to a list

         for (int i = 0; i < sectionListTemp.Length; ++i)
         {
            sectionList.Add(sectionListTemp[i]);
         }

         return sectionList;
      }

      #endregion
   }
}
