/**
 * bridge.js - SketchUp Callback Bridge
 * 通过拦截 XMLHttpRequest 将 HTTP 请求转为 SketchUp callback 调用
 * 无需 axios 为全局变量，兼容所有 webpack 打包方式
 */
(function() {
  'use strict';

  // 仅在 SketchUp 环境中启用拦截
  if (typeof window.sketchup === 'undefined') return;

  // 请求 ID 计数器
  var _requestId = 0;

  // 待处理请求映射 { id: { resolve, reject, xhr } }
  var _pendingRequests = {};

  /**
   * 全局回调：Ruby 端调用此函数返回数据
   */
  window.callback_resolve = function(id, data) {
    var pending = _pendingRequests[id];
    if (pending) {
      delete _pendingRequests[id];

      var responseText = (typeof data === 'string') ? data : JSON.stringify(data);

      // 模拟 XHR 响应
      var xhr = pending.xhr;
      Object.defineProperty(xhr, 'readyState', { writable: true, value: 4 });
      Object.defineProperty(xhr, 'status', { writable: true, value: 200 });
      Object.defineProperty(xhr, 'statusText', { writable: true, value: 'OK' });
      Object.defineProperty(xhr, 'responseText', { writable: true, value: responseText });
      Object.defineProperty(xhr, 'response', { writable: true, value: responseText });

      // 触发事件
      if (xhr.onreadystatechange) xhr.onreadystatechange();
      if (xhr.onload) xhr.onload();
    }
  };

  /**
   * 全局回调：Ruby 端调用此函数返回错误
   */
  window.callback_reject = function(id, error) {
    var pending = _pendingRequests[id];
    if (pending) {
      delete _pendingRequests[id];

      var xhr = pending.xhr;
      Object.defineProperty(xhr, 'readyState', { writable: true, value: 4 });
      Object.defineProperty(xhr, 'status', { writable: true, value: 0 });
      Object.defineProperty(xhr, 'statusText', { writable: true, value: error || 'Error' });
      Object.defineProperty(xhr, 'responseText', { writable: true, value: '' });

      if (xhr.onreadystatechange) xhr.onreadystatechange();
      if (xhr.onerror) xhr.onerror();
    }
  };

  // 保存原始 XMLHttpRequest
  var OriginalXHR = window.XMLHttpRequest;

  // 自定义 XMLHttpRequest
  function BridgeXHR() {
    this._method = '';
    this._url = '';
    this._headers = {};
    this._intercepted = false;
    this.readyState = 0;
    this.status = 0;
    this.statusText = '';
    this.responseText = '';
    this.response = '';
    this.onreadystatechange = null;
    this.onload = null;
    this.onerror = null;
    this.ontimeout = null;
  }

  BridgeXHR.prototype.open = function(method, url) {
    this._method = method;
    this._url = url;

    // 判断是否是本地 API 请求需要拦截
    // 拦截所有非外部 URL 的请求（外部 = http(s)://非本地地址）
    var isExternalUrl = /^https?:\/\/(?!localhost|127\.0\.0\.1)/.test(url);
    var isLocalApi = !isExternalUrl;

    if (isLocalApi) {
      this._intercepted = true;
    } else {
      // 非本地 API 请求，使用原始 XHR
      this._realXHR = new OriginalXHR();
      this._realXHR.open.apply(this._realXHR, arguments);
    }
  };

  BridgeXHR.prototype.setRequestHeader = function(name, value) {
    this._headers[name] = value;
    if (this._realXHR) {
      this._realXHR.setRequestHeader(name, value);
    }
  };

  BridgeXHR.prototype.send = function(body) {
    if (!this._intercepted) {
      // 非拦截的请求，走原始 XHR
      var self = this;
      if (this._realXHR) {
        this._realXHR.onreadystatechange = function() {
          self.readyState = self._realXHR.readyState;
          if (self._realXHR.readyState === 4) {
            self.status = self._realXHR.status;
            self.statusText = self._realXHR.statusText;
            self.responseText = self._realXHR.responseText;
            self.response = self._realXHR.response;
          }
          if (self.onreadystatechange) self.onreadystatechange();
        };
        this._realXHR.onload = function() { if (self.onload) self.onload(); };
        this._realXHR.onerror = function() { if (self.onerror) self.onerror(); };
        this._realXHR.send(body);
      }
      return;
    }

    // 拦截的请求 → 走 callback
    var id = ++_requestId;
    var url = this._url;

    // 提取 path
    var path = url.replace(/^https?:\/\/[^\/]+/, '').split('?')[0];
    if (!path.startsWith('/')) path = '/' + path;

    // 提取 params
    var params = {};
    var queryStr = url.split('?')[1];
    if (queryStr) {
      queryStr.split('&').forEach(function(pair) {
        var parts = pair.split('=');
        if (parts[0]) {
          params[decodeURIComponent(parts[0].replace(/\+/g, ' '))] = decodeURIComponent((parts[1] || '').replace(/\+/g, ' '));
        }
      });
    }

    // 如果有 body，合并到 params
    if (body) {
      try {
        var bodyObj = JSON.parse(body);
        for (var key in bodyObj) {
          params[key] = bodyObj[key];
        }
      } catch(e) {}
    }

    _pendingRequests[id] = {
      xhr: this
    };

    // 调用 SketchUp callback
    var payload = JSON.stringify({
      id: id,
      path: path,
      params: params
    });

    window.sketchup.api_request(payload);
  };

  BridgeXHR.prototype.abort = function() {
    if (this._realXHR) {
      this._realXHR.abort();
      return;
    }
    // 拦截的请求：清理待处理映射并触发 onabort
    if (this._intercepted) {
      for (var id in _pendingRequests) {
        if (_pendingRequests[id].xhr === this) {
          delete _pendingRequests[id];
          break;
        }
      }
      Object.defineProperty(this, 'readyState', { writable: true, value: 4 });
      Object.defineProperty(this, 'status', { writable: true, value: 0 });
      if (this.onabort) this.onabort();
    }
  };

  BridgeXHR.prototype.getResponseHeader = function(name) {
    if (this._realXHR) return this._realXHR.getResponseHeader(name);
    if (name.toLowerCase() === 'content-type') return 'application/json;charset=utf-8';
    return null;
  };

  BridgeXHR.prototype.getAllResponseHeaders = function() {
    if (this._realXHR) return this._realXHR.getAllResponseHeaders();
    return 'content-type: application/json;charset=utf-8\r\n';
  };

  // 替换全局 XMLHttpRequest
  window.XMLHttpRequest = BridgeXHR;
})();
