#include "Precompiled.h"
#include "SharedIncludes.h"
//==================================================================================================

static bool IsInCmdEditor(bool& isUnicodeFileName)
{
   isUnicodeFileName = false;
   PWSTR pszFileName = nullptr;
   size_t capacity, len;
   if (!(
      ( capacity = ::Info.EditorControl( -1, ECTL_GETFILENAME, 0, NULL ) ) &&
      ( pszFileName = (PWCHAR)malloc(capacity*2) ) &&
      ::Info.EditorControl( -1, ECTL_GETFILENAME, capacity, pszFileName ) == capacity &&
      ( len = wcslen(pszFileName) ) >= 4 ))
   {
      free( pszFileName );
      return false;
   }
   $DBG_PRINT( pszFileName );
   const PWCHAR pcszEOS = pszFileName + len;
   bool isCmdOrCmdBak =
      !_wcsicmp( pcszEOS-4, L".cmd" ) ||
      len >= 8 && !_wcsicmp( pcszEOS-8, L".cmd.bak" );
   bool rslt = isCmdOrCmdBak ||
      !_wcsicmp( pcszEOS-4, L".bat" );
      len >= 8 && !_wcsicmp( pcszEOS-8, L".cmd.bak" ) ||
      len >= 10 && !_wcsicmp( pcszEOS-10, L".CmdIn.txt" ) ||
      len >= 11 && (
         !_wcsicmp( pcszEOS-11, L".CmdOut.txt" ) ||
         !_wcsicmp( pcszEOS-11, L".CmdOut.tmp" ) ) ||
      len >= 15 &&
         !_wcsicmp( pcszEOS-15, L".CmdTempOut.txt" );
   if ( isCmdOrCmdBak )
   {
      PWSTR pszFName = nullptr;
      for (PWCHAR pch=pszFileName+len-1; pch>=pszFileName; pch--)
         if ( wcschr( L"\\/", *pch ) )
         {
            pszFName = pch + 1;
            break;
         }
      isUnicodeFileName = pszFName && wcschr( L"@#", *pszFName );
   }
   free( pszFileName );
   return rslt;
}

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

bool SwitchToCodePage()
{
   bool isUnicodeFileName;
   if ( !IsInCmdEditor( isUnicodeFileName ) )
      return false;
   $DBG_PRINT( isUnicodeFileName ?
      L"* Switching to UTF-8 code page ..." :
      L"* Switching to OEM code page ..." );
   EditorSetParameter setParam;
   $CLEAR_VAR( setParam );
   setParam.StructSize = sizeof( EditorSetParameter );
   setParam.Type = ESPT_CODEPAGE;
   setParam.iParam = isUnicodeFileName ?
      CP_UTF8 : // 65001
      ::GetOEMCP();
   if ( ::Info.EditorControl( -1, ECTL_SETPARAM, 0, &setParam ) )
      return true;
   $DBG_PRINT( L"FAILURE" );
   return false;
}

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