context: /*
  * Copyright (c) 2014 Universal Technical Resource Services, Inc.
  * 
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  */
  
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Linq;
  using System.Runtime.CompilerServices;
  using System.Security.AccessControl;
  using System.Threading;
  using System.Windows.Forms;
  using ATMLModelLibrary.interfaces;
  using ATMLModelLibrary.model;
  using ATMLModelLibrary.model.common;
  using ATMLModelLibrary.model.equipment;
  using ATMLModelLibrary.model.uut;
  using ATMLUtilitiesLibrary;
  using Path = System.IO.Path;
  
  namespace ATMLManagerLibrary.managers
  {
      public delegate void FileSavedHandler(object sender, string fileName, byte[] content, AtmlFileType atmlFileType);
  
      /**
       * Provides common file access management methods. The FileManager is implemented as a Singleton
       * where a single instance is shared throught the application.
       * @author Paul Garrison
       * @date January 2014
       */
  
      public class FileManager
      {
          private static FileManager _instance;
          private FileSystemWatcher _fileWatcher;
  
          private FileManager()
          {
          }
  
          public static void RenameProjectFiles( string projectPath, string oldName, string newName )
          {
              List<string> fileList = new List<string>();
              GetFileNames(fileList, projectPath, true, "*" + oldName + "*.*");
              int i = 0;
          }
  
  
          public void RenameFile( string oldName, string newName )
          {
              FileInfo fi = new FileInfo( oldName );
              fi.MoveTo( newName );
          }
  
  
          public FileSystemWatcher FileWatcher
          {
              set { _fileWatcher = value; }
          }
  
          /**
           * Return a common instance of the FileManager object.
           */
  
          [MethodImpl( MethodImplOptions.Synchronized )]
          public static FileManager getInstance()
          {
              if (_instance == null)
              {
                  _instance = new FileManager();
              }
              return _instance;
          }
  
          public static bool FileExists( string fileName )
          {
              return File.Exists( fileName );
          }
  
  
          /**
           * Set the project file that gets monitored for changes such as;
           * new files, file deletions, file renaming and content changes. 
           * All subdirectories will be monitored.
           */
  
          public static void SetFolderToMonitor( string folder )
          {
              getInstance().InitiFileWatcher( folder );
          }
  
          /**
           * Call to initialize a File Watcher
           */
          private void InitiFileWatcher( string path )
          {
              if (_fileWatcher == null)
              {
                  _fileWatcher = new FileSystemWatcher();
                  _fileWatcher.IncludeSubdirectories = true;
                  _fileWatcher.NotifyFilter = NotifyFilters.LastAccess |
                                              NotifyFilters.LastWrite |
                                              NotifyFilters.FileName |
                                              NotifyFilters.DirectoryName;
                  _fileWatcher.Changed += _fileWatcher_Changed;
                  _fileWatcher.Created += _fileWatcher_Created;
                  _fileWatcher.Deleted += _fileWatcher_Deleted;
                  _fileWatcher.Renamed += _fileWatcher_Renamed;
              }
              _fileWatcher.Path = path;
              _fileWatcher.EnableRaisingEvents = true;
          }
  
          /**
           * File renamed File Watcher Handler.
           */
          private void _fileWatcher_Renamed( object sender, RenamedEventArgs e )
          {
              Console.WriteLine( "{0} - File {1} has been renamed to {2}", DateTime.Now.ToString( "yyyy-MM-dd H:mm:ss" ),
                                 e.OldName, e.Name );
          }
  
          /**
           * File deleted File Watcher Handler.
           */
          private void _fileWatcher_Deleted(object sender, FileSystemEventArgs e)
          {
              Console.WriteLine( "{0} - File {1} has been deleted", DateTime.Now.ToString( "yyyy-MM-dd H:mm:ss" ), e.Name );
          }
  
          /**
           * File created File Watcher Handler.
           */
          private void _fileWatcher_Created(object sender, FileSystemEventArgs e)
          {
              Console.WriteLine( "{0} - File {1} has been created", DateTime.Now.ToString( "yyyy-MM-dd H:mm:ss" ), e.Name );
          }
  
          /**
           * File changed File Watcher Handler.
           */
          private void _fileWatcher_Changed(object sender, FileSystemEventArgs e)
          {
              Console.WriteLine( "{0} - File {1} has been changed", DateTime.Now.ToString( "yyyy-MM-dd H:mm:ss" ), e.Name );
          }
  
  
          /**
           * Displays the file open dialog to allow the user to open an XML file. The directory
           * will not be restored to it's original position, but remain where the file was opened.
           * <br/><br/>
           * <strong>Usage:</strong><br/>
           * <pre>
           *      String xmlData;
           *      if( FileManager.OpenXmlFile( out xmlData ) )
           *      {
           *          // Do Something with xmlData
           *      }
           * </pre>
           * @param[out] xmlContent - The content of the selected file
           * @return true if a file was selected
           */
  
          public static bool OpenXmlFile( out String xmlContent )
          {
              String fileName = "";
              return OpenFile( out xmlContent, out fileName, "XML files (*.xml)|*.xml|All files (*.*)|*.*" );
          }
  
          /**
           * Call to open an XML file. This method will open the Open File Dialog using a *.xml filter.
           * @param out xmlContent - will contain the xml file contents
           * @param out fileName - will contain the selected file name
           */
          public static bool OpenXmlFile( out String xmlContent, out String fileName )
          {
              return OpenFile( out xmlContent, out fileName, "XML files (*.xml)|*.xml|All files (*.*)|*.*" );
          }
  
          /**
           * Call to open a file. This method will open the Open File Dialog using the filter provided.
           * @param out xmlContent - will contain the xml file contents
           * @param out fileName - will contain the selected file name
           * @param filter - file filter to use to restrict files listed for selection.
           */
          public static bool OpenFile(out String xmlContent, out String fileName, String filter)
          {
              bool fileOpened = false;
              xmlContent = "";
              fileName = "";
              Stream inputStream = null;
              var openFileDlg = new OpenFileDialog();
  
              openFileDlg.Filter = filter;
              openFileDlg.FilterIndex = 1;
              openFileDlg.RestoreDirectory = false;
  
              if (openFileDlg.ShowDialog() == DialogResult.OK)
              {
                  try
                  {
                      fileName = openFileDlg.FileName;
                      if (( inputStream = openFileDlg.OpenFile() ) != null)
                      {
                          using (inputStream)
                          {
                              var reader = new StreamReader( inputStream );
                              xmlContent = reader.ReadToEnd();
                              reader.Close();
                              fileOpened = true;
                          }
                      }
                  }
                  catch (Exception ex)
                  {
                      MessageBox.Show( String.Format( MessageManager.getMessage( "FileManager.ReadFileError" ), ex.Message ) );
                  }
              }
              return fileOpened;
          }
  
          public static bool OpenFile( out byte[] byteContent, out FileInfo fileInfo )
          {
              bool results = OpenFile( out byteContent, out fileInfo, "All files (*.*)|*.*" );
              return results;
          }
  
          public static bool OpenFile( out byte[] byteContent, out FileInfo fileInfo, String filter )
          {
              bool fileOpened = false;
              fileInfo = null;
              byteContent = new byte[] {};
              string fileName = "";
              var openFileDlg = new OpenFileDialog();
  
              openFileDlg.Filter = filter;
              openFileDlg.FilterIndex = 1;
              openFileDlg.RestoreDirectory = false;
  
  
              if (openFileDlg.ShowDialog() == DialogResult.OK)
              {
                  try
                  {
                      fileName = openFileDlg.FileName;
                      fileInfo = new FileInfo( fileName );
                      byteContent = File.ReadAllBytes( fileName );
                      fileOpened = true;
                  }
                  catch (Exception ex)
                  {
                      MessageBox.Show( String.Format( MessageManager.getMessage( "FileManager.ReadFileError" ), ex.Message ) );
                  }
              }
              return fileOpened;
          }
  
  
          /**
           * Displays the Folder Selection dialog and returns the selected path.
           * <br/><br/>
           * <strong>Usage:</strong><br/>
           * <pre>
           *      String selectedPath;
           *      if( FileManager.OpenFolder( out selectedPath ) )
           *      {
           *          // Do Something with selectedPath
           *      }
           * </pre>
           * @param[out] selectedPath - The selected path
           * @return true if a path was selected
           */
  
          public static bool OpenFolder( out String selectedPath )
          {
              bool opened = false;
              selectedPath = null;
              var browser = new FolderBrowserDialog();
              if (DialogResult.OK == browser.ShowDialog())
              {
                  selectedPath = browser.SelectedPath;
                  opened = true;
              }
              return opened;
          }
  
  
          /**
           * Returns a list of sub folders found in the starting location provided.
           * @param[in] startingLocation - The starting location (directory)
           * @return a list of strings containing the names of all the sub directories in the starting location.
           */
  
          public static List<string> GetFolderNames( string startingLocation )
          {
              var folders = new List<string>();
              var di = new DirectoryInfo( startingLocation );
              foreach (DirectoryInfo subDir in di.EnumerateDirectories())
              {
                  folders.Add( subDir.Name );
              }
              return folders;
          }
  
          public static bool WriteFile( byte[] fileContent )
          {
  
gt:             return WriteFile( fileContent, null );