// Copyright (C) 2003-2026, Foxit Software Inc..
// All Rights Reserved.
//
// http://www.foxitsoftware.com
//
// The following code is copyrighted and contains proprietary information and trade secrets of Foxit Software Inc..
// You cannot distribute any part of Foxit PDF SDK to any third party or general public,
// unless there is a separate license agreement with Foxit Software Inc. which explicitly grants you such rights.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to operate graphics objects in OFD documents.

// Include Foxit SDK header files.
#include <iostream>
#if defined(_WIN32) || defined(_WIN64)
#include <direct.h>
#else
#include <sys/stat.h>
#endif

#include "common/fs_common.h"
#include "common/fs_image.h"
#include "ofd/fs_ofdpackage.h"
#include "ofd/fs_ofddoc.h"
#include "ofd/fs_ofdlayer.h"
#include "ofd/graphics/fs_ofdgraphicsobject.h"
#include "ofd/graphics/fs_ofdtextobject.h"
#include "ofd/graphics/fs_ofdpathobject.h"
#include "ofd/graphics/fs_ofdimageobject.h"
#include "ofd/graphics/fs_ofdcompositeobject.h"
#include "ofd/graphics/fs_ofdblockobject.h"
#include "ofd/graphics/fs_ofdvideoobject.h"
#include "ofd/annots/fs_ofdannot.h"
#include "ofd/fs_ofdpage.h"

using namespace std;
using namespace foxit;
using namespace foxit::common;
using foxit::common::Library;
using namespace foxit::ofd;
using namespace foxit::ofd::graphics;

static const char* sn = "fpj42y0uOGt8cNp2iJUJdW5LNQGpJDawgJ5niOHYLl+0Emd0mMDhtA==";
static const char* key = "8f3gFsNtvW8N+Vea402IXXgHXIciB/Uw21sIKl1s0+MWvuGiCwz8VVTEwrNsIr1uDlREGorTmUmz7lEC6UcgWUsLrWhG6ezQc5PcgosYOpKsVTaOCyFdxIVCIj7QY9pjCyDgAV1S24QKmBz/ayQSbCepuRh2MBANca27kAN9Frb1qZXYI6Bmrr08YesEz5YKDHFyC04BbHhHiCKBeoQQXzf3O8KST9cFlArWUdIIz2/c3cMjj8uuxFiqVskJrKA1wxvsW4TzZEnDldm9Aye/mZIgHOhIlf8Hg1gIvnA0GCnWhUOs2UpRSFd8YuSnm0UPI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Vjyujj15uCNDSpn4wcs32F2+wfY03pvsv+XMCrYZxvYYDHtw==";

#if defined(_WIN32) || defined(_WIN64)
static WString output_path = WString::FromLocal("../output_files/");
static WString input_path = WString::FromLocal("../input_files/");
#else
static WString output_path = WString::FromLocal("./output_files/");
static WString input_path = WString::FromLocal("./input_files/");
#endif

class SdkLibMgr {
public:
  SdkLibMgr() : is_initialize_(false) {};
  ErrorCode Initialize() {
    ErrorCode error_code = Library::Initialize(sn, key);
    if (error_code != foxit::e_ErrSuccess) {
      printf("Library Initialize Error: %d\n", error_code);
    } else {
      is_initialize_ = true;
    }
    return error_code;
  }
  ~SdkLibMgr() {
    if (is_initialize_)
      Library::Release();
  }
private:
  bool is_initialize_;
};

const char* GetObjectTypeName(OFDLayer::GraphicsObjectType type) {
  switch (type) {
    case OFDLayer::e_GraphicsObjectTypeText: return "Text";
    case OFDLayer::e_GraphicsObjectTypePath: return "Path";
    case OFDLayer::e_GraphicsObjectTypeImage: return "Image";
    case OFDLayer::e_GraphicsObjectTypeVideo: return "Video";
    case OFDLayer::e_GraphicsObjectTypeComposite: return "Composite";
    case OFDLayer::e_GraphicsObjectTypePageBlock: return "PageBlock";
    case OFDLayer::e_GraphicsObjectTypeLayer: return "Layer";
    default: return "Unknown";
  }
}

int main(int argc, char* argv[])
{
  WString output_directory = output_path + L"ofd_graphics_objects/";
#if defined(_WIN32) || defined(_WIN64)
  _mkdir(String::FromUnicode(output_directory));
#else
  mkdir(String::FromUnicode(output_directory), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif

  int err_ret = 0;
  SdkLibMgr sdk_lib_mgr;
  // Initialize library
  ErrorCode error_code = sdk_lib_mgr.Initialize();
  if (error_code != foxit::e_ErrSuccess) {
    return 1;
  }

  // Enumerate graphics objects in OFD page
  try {
    cout << "Start: Enumerate graphics objects in OFD page." << endl;
    {
      WString input_file = input_path + L"sample.ofd";

      OFDPackage pkg(input_file);
      if (pkg.IsEmpty()) {
        cout << "Failed to open OFD package." << endl;
        return 1;
      }

      OFDDoc doc = pkg.LoadDocument(0, "");
      if (doc.IsEmpty()) {
        cout << "Failed to load OFD document." << endl;
        return 1;
      }

      int page_count = doc.GetPageCount();
      cout << "Document page count: " << page_count << endl;

      for (int p = 0; p < page_count && p < 3; p++) {
        OFDPage page = doc.GetPage(p);
        int layer_count = page.GetLayerCount();
        cout << "Page " << p << " layer count: " << layer_count << endl;

        for (int l = 0; l < layer_count; l++) {
          OFDLayer layer = page.GetLayer(l);
          int obj_count = layer.GetGraphicsObjectCount();
          cout << "  Layer " << l << " object count: " << obj_count << endl;

          for (int i = 0; i < obj_count; i++) {
            OFDLayer::GraphicsObjectType obj_type = layer.GetGraphicsObjectType(i);
            OFDGraphicsObject obj = layer.GetGraphicsObject(i);

            cout << "    Object[" << i << "]: type=" << GetObjectTypeName(obj_type)
                 << ", id=" << obj.GetID() << endl;

            RectF boundary = obj.GetBoundary();
            cout << "      Boundary: left=" << boundary.left
                 << ", top=" << boundary.top
                 << ", right=" << boundary.right
                 << ", bottom=" << boundary.bottom << endl;

            // Read specific object properties based on type
            if (obj_type == OFDLayer::e_GraphicsObjectTypeText) {
              OFDTextObject text_obj(obj);
              if (!text_obj.IsEmpty()) {
                WString font_name = text_obj.GetFontName();
                float font_size = text_obj.GetFontSize();
                cout << "      Font: " << (FX_LPCSTR)String::FromUnicode(font_name)
                     << ", Size: " << font_size << endl;
              }
            } else if (obj_type == OFDLayer::e_GraphicsObjectTypePath) {
              OFDPathObject path_obj(obj);
              if (!path_obj.IsEmpty()) {
                bool is_fill = path_obj.IsFill();
                bool is_stroke = path_obj.IsStroke();
                cout << "      Fill: " << (is_fill ? "true" : "false")
                     << ", Stroke: " << (is_stroke ? "true" : "false") << endl;
              }
            } else if (obj_type == OFDLayer::e_GraphicsObjectTypeImage) {
              OFDImageObject img_obj(obj);
              if (!img_obj.IsEmpty()) {
                foxit::common::Image::Type format = img_obj.GetImageFormat();
                cout << "      Image format: " << (int)format << endl;
              }
            } else if (obj_type == OFDLayer::e_GraphicsObjectTypeVideo) {
              OFDVideoObject video_obj(obj);
              if (!video_obj.IsEmpty()) {
                String video_type = video_obj.GetVideoType();
                String video_format = video_obj.GetFormat();
                cout << "      Video type: " << (FX_LPCSTR)video_type
                     << ", format: " << (FX_LPCSTR)video_format << endl;
              }
            }
          }
        }
      }
    }
    cout << "End: Enumerate graphics objects." << endl;
  } catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }

  // Add text object to OFD page
  try {
    cout << "Start: Add text object to OFD page." << endl;
    {
      WString input_file = input_path + L"sample.ofd";
      WString output_file = output_directory + L"add_text_object.ofd";

      OFDPackage pkg(input_file);
      if (pkg.IsEmpty()) {
        cout << "Failed to open OFD package." << endl;
        err_ret = 1;
      } else {
        OFDDoc doc = pkg.LoadDocument(0, "");
        if (doc.IsEmpty()) {
          cout << "Failed to load OFD document." << endl;
          err_ret = 1;
        } else {
          OFDPage page = doc.GetPage(0);
          OFDLayer layer = page.AddLayer();

          OFDTextObject text_obj = layer.AddTextObject();
          text_obj.SetBoundary(RectF(20.0f, 20.0f, 150.0f, 40.0f));
          text_obj.SetFontName(L"SimSun");
          text_obj.SetFontSize(5.0f);
          text_obj.SetFillColor(0x000000);
          text_obj.InsertText("Hello OFD Graphics Objects!", 0.0f, 5.0f);

          cout << "Text object added successfully." << endl;

          pkg.SaveAs(output_file);
          cout << "Output file: add_text_object.ofd" << endl;
        }
      }
    }
    cout << "End: Add text object." << endl;
  } catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }

  // Add path object to OFD page
  try {
    cout << "Start: Add path object to OFD page." << endl;
    {
      WString input_file = input_path + L"sample.ofd";
      WString output_file = output_directory + L"add_path_object.ofd";

      OFDPackage pkg(input_file);
      if (pkg.IsEmpty()) {
        cout << "Failed to open OFD package." << endl;
        err_ret = 1;
      } else {
        OFDDoc doc = pkg.LoadDocument(0, "");
        if (doc.IsEmpty()) {
          cout << "Failed to load OFD document." << endl;
          err_ret = 1;
        } else {
          OFDPage page = doc.GetPage(0);
          OFDLayer layer = page.AddLayer();

          // Draw a rectangle path
          OFDPathObject path_obj = layer.AddPathObject();
          path_obj.SetBoundary(RectF(30.0f, 50.0f, 130.0f, 100.0f));
          path_obj.SetStrokeColor(0xFF0000);
          path_obj.SetLineWidth(0.5f);
          path_obj.SetStroke(true);
          path_obj.SetFill(false);

          OFDPathData path_data;
          path_data.StartFigure(0.0f, 0.0f);
          path_data.LineTo(100.0f, 0.0f);
          path_data.LineTo(100.0f, 50.0f);
          path_data.LineTo(0.0f, 50.0f);
          path_data.CloseFigure();
          path_obj.SetPathData(path_data);

          cout << "Path object (rectangle) added successfully." << endl;

          // Draw a triangle path
          OFDPathObject triangle_obj = layer.AddPathObject();
          triangle_obj.SetBoundary(RectF(30.0f, 110.0f, 130.0f, 160.0f));
          triangle_obj.SetFillColor(0x00FF00);
          triangle_obj.SetFill(true);
          triangle_obj.SetStroke(false);

          OFDPathData tri_path;
          tri_path.StartFigure(50.0f, 0.0f);
          tri_path.LineTo(100.0f, 50.0f);
          tri_path.LineTo(0.0f, 50.0f);
          tri_path.CloseFigure();
          triangle_obj.SetPathData(tri_path);

          cout << "Path object (triangle) added successfully." << endl;

          pkg.SaveAs(output_file);
          cout << "Output file: add_path_object.ofd" << endl;
        }
      }
    }
    cout << "End: Add path object." << endl;
  } catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }

  // Add image object to OFD page
  try {
    cout << "Start: Add image object to OFD page." << endl;
    {
      WString input_file = input_path + L"sample.ofd";
      WString output_file = output_directory + L"add_image_object.ofd";

      OFDPackage pkg(input_file);
      if (pkg.IsEmpty()) {
        cout << "Failed to open OFD package." << endl;
        err_ret = 1;
      } else {
        OFDDoc doc = pkg.LoadDocument(0, "");
        if (doc.IsEmpty()) {
          cout << "Failed to load OFD document." << endl;
          err_ret = 1;
        } else {
          OFDPage page = doc.GetPage(0);
          OFDLayer layer = page.AddLayer();

          OFDImageObject img_obj = layer.AddImageObject();
          img_obj.SetBoundary(RectF(30.0f, 170.0f, 100.0f, 220.0f));

          WString image_file = input_path + L"sdk.png";
          foxit::uint32 res_id = img_obj.SetImage(String::FromUnicode(image_file));
          cout << "Image object added successfully, resource id: " << res_id << endl;

          pkg.SaveAs(output_file);
          cout << "Output file: add_image_object.ofd" << endl;
        }
      }
    }
    cout << "End: Add image object." << endl;
  } catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }

  // Read and modify graphics object properties
  try {
    cout << "Start: Read and modify graphics object properties." << endl;
    {
      WString input_file = input_path + L"sample.ofd";
      WString output_file = output_directory + L"modify_object.ofd";

      OFDPackage pkg(input_file);
      if (pkg.IsEmpty()) {
        cout << "Failed to open OFD package." << endl;
        err_ret = 1;
      } else {
        OFDDoc doc = pkg.LoadDocument(0, "");
        if (doc.IsEmpty()) {
          cout << "Failed to load OFD document." << endl;
          err_ret = 1;
        } else {
          OFDPage page = doc.GetPage(0);
          int layer_count = page.GetLayerCount();

          if (layer_count > 0) {
            OFDLayer layer = page.GetLayer(0);
            int obj_count = layer.GetGraphicsObjectCount();

            for (int i = 0; i < obj_count; i++) {
              OFDGraphicsObject obj = layer.GetGraphicsObject(i);

              // Read common properties
              foxit::uint32 obj_id = obj.GetID();
              RectF boundary = obj.GetBoundary();
              Matrix mt = obj.GetMatrix();
              foxit::uint8 alpha = obj.GetAlpha();
              float line_width = obj.GetLineWidth();

              cout << "Object[" << i << "]: id=" << obj_id
                   << ", alpha=" << (int)alpha
                   << ", line_width=" << line_width << endl;

              // Modify alpha for first object
              if (i == 0) {
                obj.SetAlpha(128);
                obj.SetName("modified_object");
                cout << "  Modified alpha to 128 and set name." << endl;
              }
            }
          }

          pkg.SaveAs(output_file);
          cout << "Output file: modify_object.ofd" << endl;
        }
      }
    }
    cout << "End: Read and modify graphics object properties." << endl;
  } catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }

  return err_ret;
}
