using System;
using System.Text;

using CommonHelpers;

namespace SqlToCsvExport {

//**************************************************************************************************
partial class Scripter {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/// <exception cref="OperationFailedException" />
bool UseInsertionDef(string str,int strNo)
{
   OperationFailedException IncorrectInstructionError( string instructionName,
                                                       string message )
   {
      return OpFailedExceptionCreator.Create(HLocal.TEXT(
         "Incorrect usage of preprocessor instructions \":{0}\" in line {1}.{2} ",
         "Некорректное применение инструкции препроцессора \":{0}\" в строке {1}.{2}" ),
         instructionName, strNo, message!=null ? "\n"+message : "" );
   }
   OperationFailedException IncorrectInstructionError_SetVar( string message )
   {
      return IncorrectInstructionError( "SetVar", message );
   }

   int len = str.Length, i = 0;
   while (i<str.Length && str[i]==' ') i++;
   if ( i == len || str[i] != ':'  ) return false;
   str.Trim();

   int prefixIdx = RecognizePPPrefix( ref str, "SETVAR" );
   if ( prefixIdx < 0 )
      throw OpFailedExceptionCreator.Create(HLocal.TEXT(
         "Unknown proprocessor instrunction (\":...\") in line {0}.",
         "Неизвестная инструкция препроцессора (\":...\") в строке {0}." ),
         strNo );
   string insertionName = null;
   var spIdx = str.IndexOf( ' ' );
   if ( spIdx > 0 )
      insertionName = str.Substring( 0, spIdx );
   if ( insertionName==null || insertionName.Contains("\"") )
      throw IncorrectInstructionError_SetVar( null );
   if ( !IsNormalAsciiIdent( insertionName ) )
      throw IncorrectInstructionError_SetVar(HLocal.TEXT(
         $"Insertion name \"{insertionName}\" is not "+
         "correct identifier ASCII.",
         $"Наименование вставки \"{insertionName}\" не является "+
         "корректным идентификатором ASCII." ));
   str = str.Remove( 0, spIdx + 1 ).TrimStart();
   if (!( str.Length >= 2 && str[0] == '"' && str.EndsWith("\"") ))
      throw IncorrectInstructionError_SetVar(HLocal.TEXT(
         "String in double quotation marks was expected (\"...\").",
         "Ожидалась строка со значением в двойных кавычках (\"...\")." ));
   str = str.Remove( str.Length - 1 ).Remove( 0, 1 );
   if ( str.Contains("\"") )
      throw IncorrectInstructionError_SetVar(HLocal.TEXT(
         "Insertion value must not contain double quotes (\").",
         "Значение вставки не должно содержать двойных кавычек (\")." ));
   switch ( prefixIdx )
   {
   case 0: // SETVAR
      InsertionDictionary[ insertionName ] = str;
      break;
   default:
      throw new HAssertionFailureException();
   }
   return true;
}

int RecognizePPPrefix(ref string str,params string[] names)
{
   for (int i=0; i<names.Length; i++)
   {
      string prefix = ":" + names[ i ];
      if ( str.StartsWith( prefix + " ", StringComparison.OrdinalIgnoreCase ) ||
           HString.Equals( str, prefix, true ) )
      {
         str = str.Substring( Math.Min( prefix.Length + 1, str.Length ) ).TrimStart();
         return i;
      }
   }
   return -1;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // Scripter
//**************************************************************************************************

} // SqlToCsvExport
