//+------------------------------------------------------------------+
//|                                                   LabelBlock.mqh |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Ali Rajput"
//+------------------------------------------------------------------+
//| Includes                                                         |
//+------------------------------------------------------------------+
#include "TextWrap.mqh"
//+------------------------------------------------------------------+
//| Defines                                                          |
//+------------------------------------------------------------------+
#define TXT_MAX_LINES     999       // lines per block, from the three-digit suffix of the label names
#define TXT_SUFFIX_LEN    4         // "_" and three digits at the end of an object name
#define TXT_ERR_NOT_READY (-1)      // Set(): block not ready, nothing on the chart changed
#define TXT_ERR_CHART     (-2)      // Set(): a chart call failed, LastError() holds its error code
#define TXT_ERR_TOO_LONG  (-3)      // Set(): more than 999 lines, the last line shown says how many are missing
//+------------------------------------------------------------------+
//| ITextBlock                                                       |
//| What a text block offers, whatever draws it. Set() returns the   |
//| number of lines or one of the TXT_ERR_ codes. Verify() returns   |
//| the number of problems the block can find by itself, and what it |
//| can find depends on the block (see each class).                  |
//+------------------------------------------------------------------+
interface ITextBlock
  {
   int               Set(const string text);
   void              Clear(void);
   int               LineCount(void);
   int               Verify(void);
  };
//+------------------------------------------------------------------+
//| TextBlockLimit                                                   |
//| Keeps the first max_lines-1 lines and replaces the rest with one |
//| line that says how many lines are not shown. Returns true when   |
//| the lines were cut.                                              |
//+------------------------------------------------------------------+
bool TextBlockLimit(string &lines[],const int max_lines)
  {
   int total=ArraySize(lines);
   if(total<=max_lines)
      return(false);
   ArrayResize(lines,max_lines);
   lines[max_lines-1]=StringFormat("(%d more lines not shown)",total-max_lines+1);
   return(true);
  }
//+------------------------------------------------------------------+
//| CLabelBlock                                                      |
//| A text of any length as a stack of OBJ_LABEL objects, one per    |
//| wrapped line, each at most 63 UTF-16 code units. The objects are |
//| named <prefix>_000, <prefix>_001 and so on. The block starts at  |
//| the upper left corner of the chart, and the lines grow downward. |
//| Verify() reads the text of every label back.                     |
//+------------------------------------------------------------------+
class CLabelBlock : public ITextBlock
  {
private:
   CScreenMeter      m_meter;     // pixel widths of the font
   long              m_chart;     // chart ID
   string            m_prefix;    // start of every object name
   string            m_font;      // font name
   int               m_points;    // font size in points
   color             m_color;     // text color
   int               m_x;         // distance from the left edge, pixels
   int               m_y;         // distance from the top edge, pixels
   int               m_max_px;    // widest line, pixels
   int               m_line_step; // distance between two lines, pixels
   string            m_lines[];   // lines on the chart
   string            m_text;      // the text that produced them
   int               m_shown;     // number of labels on the chart
   int               m_calls;     // creates, deletes and text updates so far
   int               m_failed;    // chart calls of the last Set() that returned false
   int               m_last_error;// error code of the last failed chart call
   bool              m_rewrite;   // write every line at the next Set(), after a failure
   bool              m_cut;       // the last text needed more than 999 lines
   bool              m_ready;     // Init() succeeded

   string            NameOf(const int index) const;
   bool              IsOwnName(const string name) const;
   bool              Create(const int index);
   void              Failed(void);

public:
                     CLabelBlock(void);
                    ~CLabelBlock(void);
   bool              Init(const string prefix,const int x,const int y,const int max_px,
                          const string font="Arial",const int points=10,const color clr=clrBlack,
                          const int gap=2,const long chart_id=0);
   virtual int       Set(const string text);
   virtual void      Clear(void);
   virtual int       Verify(void);
   string            Line(const int index) const;
//--- access methods, written in the class body
   virtual int       LineCount(void) { return(m_shown); }
   int               ObjectCalls(void) const { return(m_calls); }
   int               FailedCalls(void) const { return(m_failed); }
   int               LastError(void) const { return(m_last_error); }
   int               Height(void) const { return(m_shown*m_line_step); }
   string            NameAt(const int index) const { return(NameOf(index)); }
  };
//+------------------------------------------------------------------+
//| CLabelBlock::CLabelBlock                                         |
//+------------------------------------------------------------------+
CLabelBlock::CLabelBlock(void) : m_chart(0),
                                 m_points(10),
                                 m_color(clrBlack),
                                 m_x(0),
                                 m_y(0),
                                 m_max_px(0),
                                 m_line_step(0),
                                 m_shown(0),
                                 m_calls(0),
                                 m_failed(0),
                                 m_last_error(0),
                                 m_rewrite(false),
                                 m_cut(false),
                                 m_ready(false)
  {
  }
//+------------------------------------------------------------------+
//| CLabelBlock::~CLabelBlock                                        |
//+------------------------------------------------------------------+
CLabelBlock::~CLabelBlock(void)
  {
   Clear();
  }
//+------------------------------------------------------------------+
//| CLabelBlock::NameOf                                              |
//+------------------------------------------------------------------+
string CLabelBlock::NameOf(const int index) const
  {
   return(m_prefix+"_"+StringFormat("%03d",index));
  }
//+------------------------------------------------------------------+
//| CLabelBlock::IsOwnName                                           |
//| True for <prefix>_ followed by exactly three digits.             |
//+------------------------------------------------------------------+
bool CLabelBlock::IsOwnName(const string name) const
  {
   int len=StringLen(m_prefix);
   if(StringLen(name)!=len+TXT_SUFFIX_LEN || StringSubstr(name,0,len+1)!=m_prefix+"_")
      return(false);
   for(int i=len+1; i<len+TXT_SUFFIX_LEN; i++)
     {
      ushort c=StringGetCharacter(name,i);
      if(c<'0' || c>'9')
         return(false);
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Failed                                              |
//| Records a chart call that returned false.                        |
//+------------------------------------------------------------------+
void CLabelBlock::Failed(void)
  {
   m_failed++;
   m_last_error=GetLastError();
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Init                                                |
//| Returns false, and leaves the block unusable, when the prefix    |
//| would make an object name longer than 63 code units, because the |
//| terminal cuts such a name without an error and two blocks could  |
//| end up sharing objects. Every label on the chart whose name is   |
//| the prefix, "_" and three digits is deleted, so that labels left |
//| by an earlier run go away even when their numbers have gaps.     |
//+------------------------------------------------------------------+
bool CLabelBlock::Init(const string prefix,const int x,const int y,const int max_px,
                       const string font="Arial",const int points=10,const color clr=clrBlack,
                       const int gap=2,const long chart_id=0)
  {
   m_ready=false;
   if(prefix=="" || StringLen(prefix)+TXT_SUFFIX_LEN>TXT_NAME_LIMIT)
      return(false);
   if(max_px<1 || points<1 || gap<0)
      return(false);
   m_chart=chart_id;
   m_prefix=prefix;
   m_font=font;
   m_points=points;
   m_color=clr;
   m_x=x;
   m_y=y;
   m_max_px=max_px;
   m_meter.Set(font,points);
   m_line_step=m_meter.LineHeight()+gap;
   m_shown=0;
   m_text="";
   m_failed=0;
   m_last_error=0;
   m_rewrite=false;
   m_cut=false;
   ArrayResize(m_lines,0);
   for(int i=ObjectsTotal(m_chart,-1,OBJ_LABEL)-1; i>=0; i--)
     {
      string name=ObjectName(m_chart,i,-1,OBJ_LABEL);
      if(IsOwnName(name))
         ObjectDelete(m_chart,name);
     }
   m_ready=true;
   return(true);
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Create                                              |
//| One new label at the position of its line. Returns false when a  |
//| chart call failed.                                               |
//+------------------------------------------------------------------+
bool CLabelBlock::Create(const int index)
  {
   string name=NameOf(index);
   m_calls++;
   ResetLastError();
   bool ok=ObjectCreate(m_chart,name,OBJ_LABEL,0,0,0);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_XDISTANCE,m_x);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_YDISTANCE,m_y+index*m_line_step);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_COLOR,m_color);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_FONTSIZE,m_points);
   ok=ok && ObjectSetInteger(m_chart,name,OBJPROP_SELECTABLE,false);
   ok=ok && ObjectSetString(m_chart,name,OBJPROP_FONT,m_font);
   if(!ok)
      Failed();
   return(ok);
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Set                                                 |
//| Wraps the text, writes only the lines that changed, and deletes  |
//| the labels that are no longer needed. The same text as the last  |
//| call is not wrapped again, so a label that was changed or        |
//| deleted outside the block comes back only after Clear(). That    |
//| early return gives the same result as the call that wrote the    |
//| text, TXT_ERR_TOO_LONG included.                                 |
//| Returns the number of lines, or:                                 |
//|  TXT_ERR_NOT_READY  the block is not ready, nothing changed      |
//|  TXT_ERR_CHART      a chart call failed, the chart may show a    |
//|                     part of the text, and the next Set() writes  |
//|                     every line again                             |
//|  TXT_ERR_TOO_LONG   the text needs more than 999 lines, the      |
//|                     block shows the first 998 and a last line    |
//|                     that says how many lines are not shown       |
//+------------------------------------------------------------------+
int CLabelBlock::Set(const string text)
  {
   if(!m_ready)
      return(TXT_ERR_NOT_READY);
   if(m_shown>0 && !m_rewrite && text==m_text)
      return(m_cut ? TXT_ERR_TOO_LONG : m_shown);
   string lines[];
   if(CTextWrap::Wrap(m_meter,text,m_max_px,TXT_LABEL_LIMIT,lines)<0)
      return(TXT_ERR_NOT_READY);
   bool cut=TextBlockLimit(lines,TXT_MAX_LINES);
   int total=ArraySize(lines);
   m_failed=0;
   for(int i=0; i<total; i++)
     {
      bool is_new=(i>=m_shown) || (m_rewrite && ObjectFind(m_chart,NameOf(i))<0);
      if(is_new && !Create(i))
         continue;
      if(is_new || m_rewrite || lines[i]!=m_lines[i])
        {
         m_calls++;
         ResetLastError();
         if(!ObjectSetString(m_chart,NameOf(i),OBJPROP_TEXT,lines[i]))
            Failed();
        }
     }
   for(int i=total; i<m_shown; i++)
     {
      m_calls++;
      ResetLastError();
      if(!ObjectDelete(m_chart,NameOf(i)) && ObjectFind(m_chart,NameOf(i))>=0)
         Failed();
     }
   ArrayResize(m_lines,total);
   for(int i=0; i<total; i++)
      m_lines[i]=lines[i];
   m_shown=total;
   m_text=text;
   m_cut=cut;
   m_rewrite=(m_failed>0);
   if(m_failed>0)
      return(TXT_ERR_CHART);
   return(cut ? TXT_ERR_TOO_LONG : total);
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Clear                                               |
//+------------------------------------------------------------------+
void CLabelBlock::Clear(void)
  {
   for(int i=0; i<m_shown; i++)
     {
      ObjectDelete(m_chart,NameOf(i));
      m_calls++;
     }
   m_shown=0;
   m_text="";
   m_rewrite=false;
   m_cut=false;
   ArrayResize(m_lines,0);
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Verify                                              |
//| Reads every label back. Returns the number of labels that are    |
//| missing or hold a text other than the line that was written.     |
//| This checks the stored text, not what the chart displays.        |
//+------------------------------------------------------------------+
int CLabelBlock::Verify(void)
  {
   int bad=0;
   for(int i=0; i<m_shown; i++)
     {
      string name=NameOf(i);
      if(ObjectFind(m_chart,name)<0 || ObjectGetString(m_chart,name,OBJPROP_TEXT)!=m_lines[i])
         bad++;
     }
   return(bad);
  }
//+------------------------------------------------------------------+
//| CLabelBlock::Line                                                |
//+------------------------------------------------------------------+
string CLabelBlock::Line(const int index) const
  {
   return((index>=0 && index<m_shown) ? m_lines[index] : "");
  }
//+------------------------------------------------------------------+
