//+-------------------------------------------------------------------+
//|                                                     PdfWriter.mqh |
//|                                 Copyright 2026, Sandro Begashvili |
//|                     https://www.mql5.com/en/users/sandrobegashvil |
//|                            Telegram: https://t.me/MrMQL5Developer |
//|                           Building a PDF Creation Library in MQL5 |
//|                                                                   |
//|                                                                   |
//|    CPdfWriter -- assembles a PDF out of numbered objects and writ |
//|    the cross-reference table from what it observed.               |
//|                                                                   |
//|    The rule this class enforces: no byte offset is ever supplied  |
//|    by a caller, and a stream length is read off the buffer at the |
//|    moment it becomes known. WriteRawStream is the one call that   |
//|    takes a count, and it clamps that count to the bytes that      |
//|    really exist rather than trusting it.                          |
//+-------------------------------------------------------------------+
#ifndef PDF5_WRITER_MQH
#define PDF5_WRITER_MQH

#include "PdfDefines.mqh"
#include "PdfBuffer.mqh"

//+-------------------------------------------------------------------+
//| CPdfWriter                                                        |
//+-------------------------------------------------------------------+
class CPdfWriter
  {
private:
   CPdfBuffer        m_out;
   int               m_offset[];
   int               m_count;
   int               m_open;
   bool              m_failed;
   bool              m_finished;

   void              Fail(const string reason);

public:
                     CPdfWriter(void) { Reset(); }

   void              Reset(void);
   bool              Begin(void);
   bool              Finish(const int root_id, const int info_id = -1);
   bool              Save(const string filename);

   int               NewObjectId(void);
   int               ObjectCount(void) const { return(m_count - 1); }
   int               OffsetOf(const int id) const;

   bool              BeginObject(const int id);
   bool              EndObject(void);

   bool              WriteDictionary(const int id, const string dictionary);
   bool              WriteStream(const int id, CPdfBuffer *content,
                                 const string extra_keys = "");
   bool              WriteRawStream(const int id, const uchar &bytes[],
                                    const int count,
                                    const string extra_keys = "");

   bool              Failed(void) const { return(m_failed); }
   int               Length(void) const { return(m_out.Length()); }
  };

//+-------------------------------------------------------------------+
//|  Reset - function                                                 |
//+-------------------------------------------------------------------+
void CPdfWriter::Reset(void)
  {
   m_out.Clear();
   ArrayResize(m_offset, 1);

//--- Object numbering starts at 1. Slot 0 is never a real object; it
//--- stands for the free-list head that every xref table begins with.
   m_offset[0] = 0;
   m_count = 1;
   m_open = -1;
   m_failed = false;
   m_finished = false;
  }

//+-------------------------------------------------------------------+
//| Records the first failure; later calls are ignored.               |
//|                                                                   |
//| Testing a return value after every append would treble the size   |
//| of the calling code for an error that only occurs when memory runs|
//| out. The first failure is remembered instead, and Save() refuses. |
//+-------------------------------------------------------------------+
void CPdfWriter::Fail(const string reason)
  {
   if(m_failed)
      return;
   m_failed = true;
   Print("CPdfWriter: ", reason);
  }

//+-------------------------------------------------------------------+
//|  Begin - function                                                 |
//+-------------------------------------------------------------------+
bool CPdfWriter::Begin(void)
  {
   Reset();

   m_out.PutLine("%PDF-" + PDF_VERSION);

//--- A comment line of four bytes above 127. It has no meaning to a
//--- reader, and its only job is to make file transfer tools treat the
//--- document as binary rather than text, which stops them from
//--- rewriting line endings and destroying every offset in the file.
   m_out.PutByte('%');
   m_out.PutByte(0xE2);
   m_out.PutByte(0xE3);
   m_out.PutByte(0xCF);
   m_out.PutByte(0xD3);
   m_out.PutText(PDF_NL);

   return(!m_failed);
  }

//+-------------------------------------------------------------------+
//| Reserves the next object number.                                  |
//|                                                                   |
//| Numbers are handed out before the objects exist, because a        |
//| catalog must reference a page tree that has not been written yet. |
//| That is  the reason PDF references objects by number at all: the  |
//| file can  be built in an order unrelated to the order it is.      |
//|  read in                                                          |
//+-------------------------------------------------------------------+
int CPdfWriter::NewObjectId(void)
  {
   if(m_count >= PDF_MAX_OBJECTS)
     {
      Fail("too many objects");
      return(-1);
     }

   if(ArrayResize(m_offset, m_count + 1) != m_count + 1)
     {
      Fail("cannot grow the offset table");
      return(-1);
     }

   m_offset[m_count] = -1;      // allocated, not yet written
   return(m_count++);
  }

//+-------------------------------------------------------------------+
//|  OffsetOf - function                                              |
//+-------------------------------------------------------------------+
int CPdfWriter::OffsetOf(const int id) const
  {
   if(id < 1 || id >= m_count)
      return(-1);
   return(m_offset[id]);
  }

//+-------------------------------------------------------------------+
//| Opens an object and records where it starts.                      |
//|                                                                   |
//| One line here is the reason the whole class exists:               |
//|                                                                   |
//|      m_offset[id] = m_out.Length();                               |
//|                                                                   |
//| The position is not predicted or maintained. It is observed at    |
//| the instant the object begins, so it is right by construction and |
//| cannot go stale when something above it changes size.             |
//+-------------------------------------------------------------------+
bool CPdfWriter::BeginObject(const int id)
  {
   if(id < 1 || id >= m_count)
     {
      Fail(StringFormat("object id %d was never allocated", id));
      return(false);
     }

   if(m_offset[id] >= 0)
     {
      Fail(StringFormat("object %d is being written twice", id));
      return(false);
     }

   if(m_open >= 0)
     {
      Fail(StringFormat("object %d was not closed before %d opened",
                        m_open, id));
      return(false);
     }

   m_offset[id] = m_out.Length();
   m_open = id;

   m_out.PutInt(id);
   m_out.PutText(" ");
   m_out.PutInt(PDF_GENERATION);
   m_out.PutLine(" obj");
   return(true);
  }

//+-------------------------------------------------------------------+
//|  EndObject - function                                             |
//+-------------------------------------------------------------------+
bool CPdfWriter::EndObject(void)
  {
   if(m_open < 0)
     {
      Fail("EndObject without BeginObject");
      return(false);
     }

   m_out.PutLine("endobj");
   m_open = -1;
   return(true);
  }

//+-------------------------------------------------------------------+
//|  WriteDictionary - function                                       |
//+-------------------------------------------------------------------+
bool CPdfWriter::WriteDictionary(const int id, const string dictionary)
  {
   if(!BeginObject(id))
      return(false);
   m_out.PutLine(dictionary);
   return(EndObject());
  }

//+-------------------------------------------------------------------+
//| Writes an object whose value is a stream.                         |
//|                                                                   |
//| The content is built in its own buffer first, so by the time the  |
//| dictionary is written the length is simply content.Length() -- a  |
//| number nobody typed and nobody can get wrong.                     |
//+-------------------------------------------------------------------+
bool CPdfWriter::WriteStream(const int id, CPdfBuffer *content,
                             const string extra_keys)
  {
   if(CheckPointer(content) == POINTER_INVALID)
     {
      Fail(StringFormat("object %d was given no content", id));
      return(false);
     }

   if(!BeginObject(id))
      return(false);

   m_out.PutText("<< /Length ");
   m_out.PutInt(content.Length());
   if(extra_keys != "")
     {
      m_out.PutText(" ");
      m_out.PutText(extra_keys);
     }
   m_out.PutLine(" >>");

   m_out.PutLine("stream");
   m_out.PutBuffer(content);
   m_out.PutText(PDF_NL);
   m_out.PutLine("endstream");

   return(EndObject());
  }

//+-------------------------------------------------------------------+
//| The same, for content that already exists as a byte array.        |
//|                                                                   |
//| Image pixels and compressed blocks arrive this way.               |
//+-------------------------------------------------------------------+
bool CPdfWriter::WriteRawStream(const int id, const uchar &bytes[],
                                const int count, const string extra_keys)
  {
//--- /Length has to equal the bytes that actually follow it, and PutArray
//--- copies no more than the array holds. The count is clamped here, and
//--- a caller who asked for more is told about it instead of being handed
//--- a stream whose length is a lie.
   int n = (count < 0) ? 0 : MathMin(count, ArraySize(bytes));
   if(n != count)
      Fail(StringFormat("object %d: /Length %d was asked for, %d bytes exist",
                        id, count, n));

   if(!BeginObject(id))
      return(false);

   m_out.PutText("<< /Length ");
   m_out.PutInt(n);
   if(extra_keys != "")
     {
      m_out.PutText(" ");
      m_out.PutText(extra_keys);
     }
   m_out.PutLine(" >>");

   m_out.PutLine("stream");
   m_out.PutArray(bytes, n);
   m_out.PutText(PDF_NL);
   m_out.PutLine("endstream");

   return(EndObject());
  }

//+-------------------------------------------------------------------+
//| Writes the cross-reference table, the trailer and %%EOF.          |
//+-------------------------------------------------------------------+
bool CPdfWriter::Finish(const int root_id, const int info_id)
  {
   if(m_finished)
     {
      Fail("Finish was already called for this document");
      return(false);
     }

   if(m_open >= 0)
     {
      Fail(StringFormat("object %d is still open", m_open));
      return(false);
     }

   if(root_id < 1 || root_id >= m_count)
     {
      Fail(StringFormat("root object %d was never allocated", root_id));
      return(false);
     }

//--- /Info is optional, but a reference to it is a promise like any other
   if(info_id > 0 && info_id >= m_count)
     {
      Fail(StringFormat("info object %d was never allocated", info_id));
      return(false);
     }

//--- Every allocated id must have been written, or the table would
//--- promise an object that is not in the file. Catching it here names
//--- the object that was forgotten.
   for(int i = 1; i < m_count; i++)
      if(m_offset[i] < 0)
        {
         Fail(StringFormat("object %d was allocated but never written", i));
         return(false);
        }

//--- The position of the word "xref" is what startxref must carry, and
//--- it is observed for the same reason every other offset is.
   int xref_at = m_out.Length();

   m_out.PutLine("xref");
   m_out.PutText("0 ");
   m_out.PutInt(m_count);
   m_out.PutText(PDF_NL);

//--- Entry 0 heads the list of free objects. Generation 65535 is the
//--- largest the field holds and never changes.
   m_out.PutPadded(0, 10);
   m_out.PutText(" 65535 f ");
   m_out.PutText(PDF_NL);

//--- Ten digits, space, five digits, space, flag, space, line ending:
//--- twenty bytes, which is what lets a viewer jump to entry i instead
//--- of reading the i-1 entries above it.
   for(int i = 1; i < m_count; i++)
     {
      m_out.PutPadded(m_offset[i], 10);
      m_out.PutText(" ");
      m_out.PutPadded(PDF_GENERATION, 5);
      m_out.PutText(" n ");
      m_out.PutText(PDF_NL);
     }

   m_out.PutLine("trailer");
   m_out.PutText("<< /Size ");
   m_out.PutInt(m_count);
   m_out.PutText(" /Root ");
   m_out.PutInt(root_id);
   m_out.PutText(" 0 R");
   if(info_id > 0)
     {
      m_out.PutText(" /Info ");
      m_out.PutInt(info_id);
      m_out.PutText(" 0 R");
     }
   m_out.PutLine(" >>");

   m_out.PutLine("startxref");
   m_out.PutInt(xref_at);
   m_out.PutText(PDF_NL);
   m_out.PutLine("%%EOF");

   m_finished = true;

//--- The appends above are not tested one by one. The buffer remembers
//--- instead, and this is where that memory is read: if any of them ran
//--- out of memory, the document is short and must not be saved.
   if(m_out.Failed())
      Fail("the buffer ran out of memory while the file was being built");

   return(!m_failed);
  }

//+-------------------------------------------------------------------+
//|  Save - function                                                  |
//+-------------------------------------------------------------------+
bool CPdfWriter::Save(const string filename)
  {
   if(!m_finished)
     {
      Print("CPdfWriter: refusing to save before Finish() wrote the xref");
      return(false);
     }

   if(m_failed || m_out.Failed())
     {
      Print("CPdfWriter: refusing to save a document that failed to build");
      return(false);
     }
   return(m_out.SaveToFile(filename));
  }

#endif // PDF5_WRITER_MQH
//+------------------------------------------------------------------+
