using System;
using System.IO;
using System.Reflection;

using System.Data;
using System.Data.SqlClient;

using CommonHelpers;

namespace SqlToCsvExport {

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

/// <exception cref="HAppFailureException" />
static void PerformExport()
{
   if ( InvolveScriptFile && !File.Exists( ScriptSource ) )
      throw HAppFailureExceptionCreator.Create(HLocal.TEXT(
         "Script file not found: \"{0}\".",
         "Не удалось обнаружить файл скрипта: \"{0}\"." ),
         ScriptSource );

   string ProgramAssemblyName() => Assembly.GetEntryAssembly().GetName().Name;

   string password = null;
   if ( UserName!=null && PasswordVariable!=null )
      password = Environment.GetEnvironmentVariable( PasswordVariable );

   _Connection_ = UserName != null ?
      new SqlConnection(string.Format(
         "Data Source={0};Initial Catalog={1};User ID={2};Password={3};Application Name={4};"+
         "Pooling=False", //";Current Language=English",
         ServerName, DatabaseName, UserName, password, ProgramAssemblyName())) :
      new SqlConnection(string.Format(
         "Integrated Security=True;Data Source={0};Initial Catalog={1};Application Name={2};"+
         "Pooling=False", //";Current Language=English",
         ServerName, DatabaseName, ProgramAssemblyName()));

   HConsole.PrintOperation(HLocal.TEXT(
      "Connecting to SQL: [{0}].[{1}]{2}",
      "Подключение к SQL: [{0}].[{1}]{2}" ),
      ServerName, DatabaseName,
      UserName!=null ? string.Format(" ({0})",UserName) : "" );
   try
      { Connection.Open(); }
   catch (SystemException e)
      { throw HAppFailureExceptionCreator.Create( e ); }

   Exception error = null;
   try
   {
      DownloadData();
   }
   catch (Exception e)
   {
      error = e;
      if ( e is OperationFailedException )
         throw HAppFailureExceptionCreator.Create( e );
      throw;
   }
   finally
   {
      try {
         HOps.NullExchange(ref _Connection_).Close(); }
      catch (SqlException e) {
         if ( error == null )
            throw HAppFailureExceptionCreator.Create( error = e ); }
   }
}

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

/// <exception cref="HAppFailureException" />
static void UseAdditionalParams()
{
   try
   {
      _UserName_ = EnvironmentVariableValue( "$sql_user" );
      _PasswordVariable_ = EnvironmentVariableValue( "$sql_password_var" );

      AdditionalParams.ObtainFlag(
         AdditionalParams.Names.InsertColHeaders,
         ref _InsertColHeaders_ );

      AdditionalParams.ObtainFlag(
         AdditionalParams.Names.InsertRecNoColumn,
         ref _InsertRecNoColumn_  );

      AdditionalParams.ObtainChar(
         AdditionalParams.Names.ColSepChar,
         ref _CsvSepChar_ );

      AdditionalParams.ObtainFlag(
         AdditionalParams.Names.EmbraceAllWithQuotes,
         ref _EmbraceAllWithQuotes_ );

      AdditionalParams.ObtainChar(
         AdditionalParams.Names.IncorrectCharSubst,
         ref _CsvIncorrectCharSubst_ );

      AdditionalParams.ObtainStr(
         AdditionalParams.Names.RecNoCaption,
         ref _CsvRecNoCaption_ );

      AdditionalParams.ObtainFlag(
         AdditionalParams.Names.SuppressAlienLetters,
         ref _SuppressAlienLetters_ );

      AdditionalParams.ObtainFlag(
         AdditionalParams.Names.ExportInUTF8,
         ref _ExportInUTF8_ );

      AdditionalParams.VerifyNames();
   }
   catch (OperationFailedException e)
   {
      throw HAppFailureExceptionCreator.Create( e );
   }
}

static string EnvironmentVariableValue(string name) =>
   name!=null ? Environment.GetEnvironmentVariable( name ) : null;

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

static bool InsertColHeaders     => _InsertColHeaders_;
static bool InsertRecNoColumn    => _InsertRecNoColumn_;
static char CsvSepChar           => _CsvSepChar_;
static bool EmbraceAllWithQuotes => _EmbraceAllWithQuotes_;
static char CsvIncorrectCharSubst=> _CsvIncorrectCharSubst_;
static string CsvRecNoCaption    => _CsvRecNoCaption_;
static bool SuppressAlienLetters => _SuppressAlienLetters_;
static bool ExportInUTF8         => _ExportInUTF8_;

//--------------------------------------------------------------------------------------------------

static string ServerName         => _ServerName_;
static string DatabaseName       => _DatabaseName_;
static string UserName           => _UserName_;
static string PasswordVariable   => _PasswordVariable_;
static string ScriptSource       => _ScriptSource_;
static string ResultFile         => _ResultFile_;
[HOptionalValue]
static string ExtendedArgument   => _ExtendedArgument_;
static SqlConnection Connection  => _Connection_;
static bool InvolveScriptFile    => _InvolveScriptFile_;
static bool InvolveStoredProc    => _InvolveStoredProc_;

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

static char
   _CsvSepChar_            = AdditionalParams.DefaultValues.ColSepChar,
   _CsvIncorrectCharSubst_ = AdditionalParams.DefaultValues.IncorrectCharSubst;
static bool
   _InsertColHeaders_      = AdditionalParams.DefaultValues.InsertColHeaders,
   _InsertRecNoColumn_     = AdditionalParams.DefaultValues.InsertRecNoColumn,
   _EmbraceAllWithQuotes_  = AdditionalParams.DefaultValues.EmbraceAllWithQuotes,
   _SuppressAlienLetters_  = AdditionalParams.DefaultValues.SuppressAlienLetters,
   _ExportInUTF8_          = AdditionalParams.DefaultValues.ExportInUTF8,
   _InvolveScriptFile_,
   _InvolveStoredProc_;
static string
   _CsvRecNoCaption_       = AdditionalParams.DefaultValues.RecNoCaption,
   _ServerName_, _DatabaseName_, _UserName_, _PasswordVariable_,
   _ScriptSource_, _ExtendedArgument_, _ResultFile_;
static SqlConnection
   _Connection_;

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

} // SqlToCsvExport
