using System;
using System.IO;
using System.Text;

using CommonHelpers;

namespace TypeInColor {

//**************************************************************************************************
static partial class Program {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public const int
   ParamIdx_Color = 0,
   ParamIdx_File  = 1;

//==================================================================================================

static ConsoleColor? ColorParameter => _Color_;
/// <exception cref="InvalidOperationException" />
static string FilePath
{
   get
   {
      if ( _FilePath_ == null )
         throw new InvalidOperationException();
      return _FilePath_;
   }
}

//==================================================================================================

/// <exception cref="ArgumentNullException" />
/// <exception cref="OperationFailedException" />
static void PerformTyping()
{
   HArgChecking.VerifyNotNull( FilePath );
   StreamReader reader;
   try
   {
      reader = new StreamReader( FilePath, Encoding.Default, true );
   }
   catch (Exception e)
   {
      throw OpFailedExceptionCreator.Create(
         "Can not open file: \"{0}\".\n"+
         "{1}", FilePath, e.Message );
   }
   Exception error = null;
   try
   {
      ProcessLines( reader );
   }
   catch (Exception e)
   {
      error = e; throw;
   }
   finally
   {
      try
      {
         reader.Close(); reader.Dispose();
      }
      catch (Exception e)
      {
         if ( error == null )
            throw OpFailedExceptionCreator.Create( error = e );
      }
   }
}
/// <exception cref="SystemException" />
/// <exception cref="OperationFailedException" />
static void ProcessLines(StreamReader reader)
{
   string READ_LINE()
   {
      try { return reader.ReadLine(); }
      catch (Exception e)
      {
         throw OpFailedExceptionCreator.Create(
            "Error when reading file: \"{0}\".\n"+
            "{1}", FilePath, e.Message );
      }
   }
   var colorValue = ColorParameter ?? HConsole.InitialForeColor;
   string str;
   while ( (str = READ_LINE()) != null )
      HConsole.Print( colorValue, str );
}

//==================================================================================================

static ConsoleColor? _Color_;
static string _FilePath_;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // Program
//**************************************************************************************************

} // TypeInColor
