using System;
using System.IO;
using System.Globalization;

using CommonHelpers;

namespace SqlToCsvExport {

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

/// <exception cref="HAppFailureException" />
public static void Run(string[] args)
{
   HConsole.PrintIntensive(HLocal.TEXT(
      "=== {0} Utility {1} ({2}): ===",
      "=== Утилита {0} {1} ({2}): ===" ),
      SqlToCsvExport_Info.AssemblyName, //Assembly.GetEntryAssembly().GetName().Name
      SqlToCsvExport_Info.VersionStringExCON,
      SqlToCsvExport_Info.LCopyrightCON );

   if ( args.Length == 0 )
   {
      PrintSyntax();
      return;
   }

   if ( !HOps.IsBetween( args.Length, 3, 4 ) )
      throw IncorrectParamsError;

   _ServerName_   = args[ 0 ].Trim();
   _DatabaseName_ = args[ 1 ].Trim();
   _ScriptSource_ = args[ 2 ].Trim();
   if ( args.Length >= 4 )
      _ExtendedArgument_ = NormalizeSQLQueryText( args[ 3 ] );

   if ( _ServerName_ == "" || _DatabaseName_ == "" || ScriptSource == "" || ExtendedArgument == "" )
      throw IncorrectParamsError;

   _InvolveScriptFile_ =
      ScriptSource.EndsWith( ".sql", true, CultureInfo.InvariantCulture );
   _InvolveStoredProc_ = !InvolveScriptFile;

   if ( InvolveScriptFile )
   {
      string sqlPathWithoutExt = null;
      try
      {
         sqlPathWithoutExt = Path.Combine(
            Path.GetDirectoryName( ScriptSource ),
            Path.GetFileNameWithoutExtension( ScriptSource ) );
      }
      catch (Exception e)
      {
         throw HAppFailureExceptionCreator.Create(HLocal.TEXT(
            "Incorrect SQL file name/path: \"{0}\" (3-rd parameter).\n"+
            "{1}",
            "Некорректное имя/путь файла SQL: \"{0}\" (3-й параметр).\n"+
            "{1}" ),
            ScriptSource, e.Message );
      }
      if  ( ExtendedArgument != null )
         try
         {
            if ( !Path.GetExtension( ExtendedArgument ).Equals(
                 ".csv", StringComparison.InvariantCultureIgnoreCase ) )
               throw new HAppFailureException(HLocal.TEXT(
                  "File extension \".csv\" was expected.",
                  "Ожидалось файловое расширение \".csv\"." ));
            _ResultFile_ = Path.Combine(
               Path.GetDirectoryName( ExtendedArgument ),
               Path.GetFileName( ExtendedArgument ) );
         }
         catch (Exception e)
         {
            throw HAppFailureExceptionCreator.Create(HLocal.TEXT(
               "Incorrect result file name/path: \"{0}\" (4-th parameter).\n"+
               "{1}",
               "Некорректное имя/путь файла результатов: \"{0}\" (4-й параметр).\n"+
               "{1}" ),
               ScriptSource, e.Message );
         }
      else
         _ResultFile_ = sqlPathWithoutExt + ".csv";
   }

   UseAdditionalParams();

   PerformExport();

   HConsole.PrintExpressive(HLocal.TEXT(
      "Done (uploading completed).",
      "Выполнено." ));
}

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

} // SqlToCsvExport
