//+------------------------------------------------------------------+
//|                                         CustomSymbolWriter.mqh   |
//|          Creates and populates a custom symbol from daily bars   |
//+------------------------------------------------------------------+
#ifndef CUSTOMSYMBOLWRITER_MQH
#define CUSTOMSYMBOLWRITER_MQH

#include "DailyAggregatorTypes.mqh"

//+-------------------------------------------------------------------+
//| CCustomSymbolWriter                                               |
//| Ensures a custom symbol exists, configures its digits, clears any |
//| pre-existing bars, and writes an array of CDailyBar records into  |
//| it.                                                               |
//+-------------------------------------------------------------------+
class CCustomSymbolWriter
  {
private:
   string            m_custom_folder;

public:
                     CCustomSymbolWriter(void);
                    ~CCustomSymbolWriter(void);

   bool              EnsureSymbolExists(const string symbol_name,bool &out_was_created);
   bool              ConfigureDigits(const string symbol_name,const string source_symbol);
   bool              ClearExistingRange(const string symbol_name);
   bool              WriteDailyBars(const string symbol_name,const CDailyBar &daily_bars[]);
  };

//+------------------------------------------------------------------+
//| CCustomSymbolWriter::CCustomSymbolWriter                         |
//| Returns: a writer that will create new custom symbols under a    |
//|          dedicated "Custom\\DailyAggregator" path in the Symbols |
//|          tree.                                                   |
//+------------------------------------------------------------------+
CCustomSymbolWriter::CCustomSymbolWriter(void)
  {
   m_custom_folder = "Custom\\DailyAggregator";
  }

//+------------------------------------------------------------------+
//| CCustomSymbolWriter::~CCustomSymbolWriter                        |
//| Returns: nothing; there is no owned resource to release.         |
//+------------------------------------------------------------------+
CCustomSymbolWriter::~CCustomSymbolWriter(void)
  {
  }

//+---------------------------------------------------------------------+
//| CCustomSymbolWriter::EnsureSymbolExists                             |
//| Returns: true if the symbol exists as a custom symbol by the end of |
//|          this call, either because it already did or because it     |
//|          was just created. Returns false on a naming collision with |
//|          a non-custom symbol, or if creation fails.                 |
//+---------------------------------------------------------------------+
bool CCustomSymbolWriter::EnsureSymbolExists(const string symbol_name,bool &out_was_created)
  {
//--- SymbolExist() reports existence via its return value and writes into
//--- is_custom whether that existing symbol is a custom one
   bool is_custom = false;
   bool exists    = ::SymbolExist(symbol_name,is_custom);
   if(exists && is_custom)
     {
      out_was_created=false;
      return(true);
     }
   if(exists && !is_custom)
     {
      //--- a real, non-custom symbol already occupies this name, refuse to proceed
      Print("CCustomSymbolWriter: '",symbol_name,"' already exists as a non-custom symbol, choose a different name");
      out_was_created = false;
      return(false);
     }
//--- the symbol does not exist yet, so create it under a dedicated custom folder
   bool created=::CustomSymbolCreate(symbol_name,m_custom_folder);
   if(!created)
     {
      Print("CCustomSymbolWriter: CustomSymbolCreate failed for ",symbol_name," error ",::GetLastError());
      out_was_created = false;
      return(false);
     }
   out_was_created = true;
   return(true);
  }

//+---------------------------------------------------------------------+
//| CCustomSymbolWriter::ConfigureDigits                                |
//| Assumptions: symbol_name already exists as a custom symbol.         |
//| Returns: true if the source symbol was selectable, its digits were  |
//|          read successfully, and CustomSymbolSetInteger() succeeded. |
//|          Returns false and logs the point of failure otherwise.     |
//+---------------------------------------------------------------------+
bool CCustomSymbolWriter::ConfigureDigits(const string symbol_name,const string source_symbol)
  {
//--- confirm the source symbol is actually selected and known to the terminal before reading from it
   if(!::SymbolSelect(source_symbol,true))
     {
      Print("CCustomSymbolWriter: source symbol '",source_symbol,"' could not be selected, error ",::GetLastError());
      return(false);
     }
//--- read digits with the boolean-returning overload, which reports success or failure explicitly
//--- instead of returning an ambiguous value when the read fails
   long source_digits=0;
   if(!::SymbolInfoInteger(source_symbol,SYMBOL_DIGITS,source_digits))
     {
      Print("CCustomSymbolWriter: failed to read SYMBOL_DIGITS from '",source_symbol,"' error ",::GetLastError());
      return(false);
     }
   bool result = ::CustomSymbolSetInteger(symbol_name,SYMBOL_DIGITS,source_digits);
   if(!result)
      Print("CCustomSymbolWriter: CustomSymbolSetInteger(SYMBOL_DIGITS) failed for ",symbol_name," error ",::GetLastError());
   return(result);
  }

//+---------------------------------------------------------------------+
//| CCustomSymbolWriter::ClearExistingRange                             |
//| Assumptions: symbol_name already exists as a custom symbol.         |
//| Returns: true once any pre-existing bars under symbol_name have     |
//|          been removed, so a rerun with a different lookback window, |
//|          a different session close hour, or corrected logic cannot  |
//|          leave stale bars behind. Returns false and logs the error  |
//|          if CustomRatesDelete() fails.                              |
//+---------------------------------------------------------------------+
bool CCustomSymbolWriter::ClearExistingRange(const string symbol_name)
  {
   int deleted=::CustomRatesDelete(symbol_name,0,D'2099.12.31 23:59:59');
   if(deleted<0)
     {
      Print("CCustomSymbolWriter: CustomRatesDelete failed for ",symbol_name," error ",::GetLastError());
      return(false);
     }
   Print("CCustomSymbolWriter: cleared ",deleted," pre-existing bars from ",symbol_name," before writing");
   return(true);
  }

//+---------------------------------------------------------------------+
//| CCustomSymbolWriter::WriteDailyBars                                 |
//| Assumptions: symbol_name already exists as a custom symbol, and     |
//|              daily_bars is in ascending chronological order.        |
//| Returns: true only if CustomRatesUpdate() reports writing exactly   |
//|          as many bars as were supplied. Returns false if daily_bars |
//|          is empty, if CustomRatesUpdate() fails outright, or if it  |
//|          writes fewer bars than requested.                          |
//+---------------------------------------------------------------------+
bool CCustomSymbolWriter::WriteDailyBars(const string symbol_name,const CDailyBar &daily_bars[])
  {
   int total = ArraySize(daily_bars);
   if(total<=0)
     {
      Print("CCustomSymbolWriter: no daily bars to write for ",symbol_name);
      return(false);
     }
//--- convert each aggregated daily bar into the MqlRates structure CustomRatesUpdate() expects
   MqlRates rates[];
   ArrayResize(rates,total);
   for(int i=0;i<total;i++)
     {
      rates[i].time         = daily_bars[i].GetOpenTime();
      rates[i].open         = daily_bars[i].GetOpen();
      rates[i].high         = daily_bars[i].GetHigh();
      rates[i].low          = daily_bars[i].GetLow();
      rates[i].close        = daily_bars[i].GetClose();
      rates[i].tick_volume  = daily_bars[i].GetVolume();
      rates[i].real_volume  = 0;
      rates[i].spread       = 0;
     }
   int written = ::CustomRatesUpdate(symbol_name,rates);
   if(written<0)
     {
      Print("CCustomSymbolWriter: CustomRatesUpdate failed for ",symbol_name," error ",::GetLastError());
      return(false);
     }
   if(written!=total)
     {
      Print("CCustomSymbolWriter: WARNING, requested ",total," bars but only ",
            written," were written for ",symbol_name,", the custom symbol may be incomplete");
      return(false);
     }
   Print("CCustomSymbolWriter: wrote ",written," daily bars to ",symbol_name);
   return(true);
  }

#endif // CUSTOMSYMBOLWRITER_MQH
//+------------------------------------------------------------------+