/**
 * CSInterface.js — Adobe CEP 12
 * Bundled with PR Transcript extension.
 * Source: https://github.com/Adobe-CEP/CEP-Resources
 */

'use strict';

// ── Constants ──────────────────────────────────────

var SystemPath = {
  HOST_APPLICATION : 0,
  COMMON_FILES     : 1,
  MY_DOCUMENTS     : 2,
  APPLICATION      : 3,
  EXTENSION        : 4,
  EXTENSION_DATA   : 5,
  USER_DATA        : 6
};

var LogLevel = {
  DEBUG : 'debug',
  INFO  : 'info',
  WARN  : 'warn',
  ERROR : 'error'
};

var APIVersion = {
  THEME_COLOR_CHANGED_EVENT : 1.1,
  ICON_NORMAL               : 1.2
};

var CSXS_VERSION = '12.0';

// ── Helper classes ─────────────────────────────────

function RGBColor(red, green, blue, alpha) {
  this.red   = red;
  this.green = green;
  this.blue  = blue;
  this.alpha = alpha;
}

function Direction(left, top, right, bottom) {
  this.left   = left;
  this.top    = top;
  this.right  = right;
  this.bottom = bottom;
}

function CSEvent(type, scope, appId, extensionId) {
  this.type        = type;
  this.scope       = scope || 'GLOBAL';
  this.appId       = appId || '';
  this.extensionId = extensionId || '';
  this.data        = '';
}

function VersionNumber(major, minor, micro, special) {
  this.major   = major   || 0;
  this.minor   = minor   || 0;
  this.micro   = micro   || 0;
  this.special = special || 0;
}

function Version(lower, upper) {
  this.lower = lower;
  this.upper = upper;
}

function AppSkinInfo(baseFontFamily, baseFontSize, appBarBackgroundColor,
                     panelBackgroundColor, appBarBackgroundColorSRGB,
                     panelBackgroundColorSRGB, systemHighlightColor) {
  this.baseFontFamily              = baseFontFamily;
  this.baseFontSize                = baseFontSize;
  this.appBarBackgroundColor       = appBarBackgroundColor;
  this.panelBackgroundColor        = panelBackgroundColor;
  this.appBarBackgroundColorSRGB   = appBarBackgroundColorSRGB;
  this.panelBackgroundColorSRGB    = panelBackgroundColorSRGB;
  this.systemHighlightColor        = systemHighlightColor;
}

function HostEnvironment(appName, appVersion, appLocale, appUILocale,
                         appId, isAppOnline, appSkinInfo) {
  this.appName      = appName;
  this.appVersion   = appVersion;
  this.appLocale    = appLocale;
  this.appUILocale  = appUILocale;
  this.appId        = appId;
  this.isAppOnline  = isAppOnline;
  this.appSkinInfo  = appSkinInfo;
}

function HostCapabilities(EXTENDED_PANEL_MENU, EXTENDED_PANEL_ICONS,
                          DELEGATE_APE_ENGINE, SUPPORT_HTML_EXTENSIONS,
                          DISABLE_FLASH_EXTENSIONS) {
  this.EXTENDED_PANEL_MENU      = EXTENDED_PANEL_MENU;
  this.EXTENDED_PANEL_ICONS     = EXTENDED_PANEL_ICONS;
  this.DELEGATE_APE_ENGINE      = DELEGATE_APE_ENGINE;
  this.SUPPORT_HTML_EXTENSIONS  = SUPPORT_HTML_EXTENSIONS;
  this.DISABLE_FLASH_EXTENSIONS = DISABLE_FLASH_EXTENSIONS;
}

function ApiVersion(major, minor, micro) {
  this.major = major;
  this.minor = minor;
  this.micro = micro;
}

// ── CSInterface ────────────────────────────────────

/**
 * @class CSInterface
 * Provides the interface for accessing Adobe CEP APIs.
 */
function CSInterface() {
  // CEP injects window.__adobe_cep__ at panel load time
  if (!window.__adobe_cep__) {
    console.warn('[CSInterface] window.__adobe_cep__ not found. ' +
                 'Ensure --enable-nodejs is in manifest CEFCommandLine ' +
                 'and PlayerDebugMode registry key is set.');
  }
}

CSInterface.THEME_COLOR_CHANGED_EVENT = 'com.adobe.csxs.events.ThemeColorChanged';
CSInterface.APPID                     = 'PPRO';

// ── evalScript ────────────────────────────────────

/**
 * Evaluate an ExtendScript snippet and invoke callback with result.
 * @param {string}   script   - ExtendScript to evaluate
 * @param {function} callback - fn(result: string)
 */
CSInterface.prototype.evalScript = function (script, callback) {
  if (!script || typeof script !== 'string') {
    if (callback) callback('EvalScript error.');
    return;
  }

  if (callback === null || callback === undefined) {
    callback = function () {};
  }

  var cep = window.__adobe_cep__;
  if (!cep) {
    console.error('[CSInterface] evalScript: __adobe_cep__ not available');
    callback('EvalScript error.');
    return;
  }

  try {
    cep.evalScript(script, callback);
  } catch (e) {
    console.error('[CSInterface] evalScript exception:', e);
    callback('EvalScript error.');
  }
};

// ── getExtensionID ────────────────────────────────

CSInterface.prototype.getExtensionID = function () {
  if (!window.__adobe_cep__) return '';
  try { return window.__adobe_cep__.getExtensionId(); } catch (e) { return ''; }
};

// ── getSystemPath ─────────────────────────────────

CSInterface.prototype.getSystemPath = function (pathType) {
  if (!window.__adobe_cep__) return '';
  try {
    var path = decodeURIComponent(window.__adobe_cep__.getSystemPath(pathType));
    // On Windows, __adobe_cep__ returns forward slashes — normalize
    if (path && path.indexOf('/') !== -1) {
      path = path.replace(/\//g, '\\');
      // Remove file:/// or file:// prefix
      path = path.replace(/^file:\\\\\\/, '').replace(/^file:\\\\/, '');
      // Remove leading backslash on Windows paths like \C:\...
      if (path.charAt(0) === '\\' && path.charAt(2) === ':') {
        path = path.slice(1);
      }
    }
    return path;
  } catch (e) {
    return '';
  }
};

// ── getOSInformation ──────────────────────────────

CSInterface.prototype.getOSInformation = function () {
  if (!window.__adobe_cep__) return '';
  try { return window.__adobe_cep__.getOsVersion(); } catch (e) { return ''; }
};

// ── getHostEnvironment ────────────────────────────

CSInterface.prototype.getHostEnvironment = function () {
  if (!window.__adobe_cep__) return null;
  try {
    var rawEnv = window.__adobe_cep__.getHostEnvironment();
    if (!rawEnv) return null;
    var env = JSON.parse(rawEnv);
    return env;
  } catch (e) {
    return null;
  }
};

// ── addEventListener ──────────────────────────────

CSInterface.prototype.addEventListener = function (type, listener, obj) {
  if (!window.__adobe_cep__) return;
  try {
    window.__adobe_cep__.addEventListener(type, listener, false);
  } catch (e) {
    console.warn('[CSInterface] addEventListener failed:', e.message);
  }
};

CSInterface.prototype.removeEventListener = function (type, listener, obj) {
  if (!window.__adobe_cep__) return;
  try {
    window.__adobe_cep__.removeEventListener(type, listener, false);
  } catch (e) {}
};

// ── dispatchEvent ─────────────────────────────────

CSInterface.prototype.dispatchEvent = function (event) {
  if (!window.__adobe_cep__) return;
  try {
    if (typeof event.data === 'object') {
      event.data = JSON.stringify(event.data);
    }
    window.__adobe_cep__.dispatchEvent(event);
  } catch (e) {}
};

// ── closeExtension ────────────────────────────────

CSInterface.prototype.closeExtension = function () {
  if (!window.__adobe_cep__) return;
  try { window.__adobe_cep__.closeExtension(); } catch (e) {}
};

// ── requestOpenExtension ──────────────────────────

CSInterface.prototype.requestOpenExtension = function (extensionId, params) {
  if (!window.__adobe_cep__) return;
  try { window.__adobe_cep__.requestOpenExtension(extensionId, params || ''); } catch (e) {}
};

// ── getScaleFactor ────────────────────────────────

CSInterface.prototype.getScaleFactor = function () {
  if (!window.__adobe_cep__) return 1;
  try { return window.__adobe_cep__.getScaleFactor(); } catch (e) { return 1; }
};

// ── setScaleFactorChangedHandler ──────────────────

CSInterface.prototype.setScaleFactorChangedHandler = function (handler) {
  if (!window.__adobe_cep__) return;
  try { window.__adobe_cep__.setScaleFactorChangedHandler(handler); } catch (e) {}
};

// ── getCurrentApiVersion ──────────────────────────

CSInterface.prototype.getCurrentApiVersion = function () {
  if (!window.__adobe_cep__) return new ApiVersion(1, 0, 0);
  try {
    var raw = window.__adobe_cep__.getCurrentApiVersion();
    var ver = JSON.parse(raw);
    return new ApiVersion(ver.major, ver.minor, ver.micro);
  } catch (e) {
    return new ApiVersion(12, 0, 0);
  }
};

// ── setPanelFlyoutMenu ────────────────────────────

CSInterface.prototype.setPanelFlyoutMenu = function (menu) {
  if (!window.__adobe_cep__) return;
  try { window.__adobe_cep__.setPanelFlyoutMenu(menu); } catch (e) {}
};

// ── updatePanelMenuItem ───────────────────────────

CSInterface.prototype.updatePanelMenuItem = function (menuItemLabel, enabled, checked) {
  if (!window.__adobe_cep__) return false;
  try {
    return window.__adobe_cep__.updatePanelMenuItem(menuItemLabel, enabled, checked);
  } catch (e) { return false; }
};

// ── openURLInDefaultBrowser ───────────────────────

CSInterface.prototype.openURLInDefaultBrowser = function (url) {
  if (!window.__adobe_cep__) return false;
  try {
    window.__adobe_cep__.openURLInDefaultBrowser(url);
    return true;
  } catch (e) { return false; }
};

// ── Expose ────────────────────────────────────────

window.CSInterface  = CSInterface;
window.SystemPath   = SystemPath;
window.LogLevel     = LogLevel;
window.CSEvent      = CSEvent;
window.RGBColor     = RGBColor;
window.Direction    = Direction;
window.Version      = Version;
window.VersionNumber = VersionNumber;
window.HostEnvironment = HostEnvironment;
window.ApiVersion   = ApiVersion;
