import {atob as _atob} from 'abab';
import _XMLHttpRequest from './XMLHttpRequest'
import copyProperties from './copyProperties'
import EventTarget from "./EventTarget"

export function createScopedThreejs(canvas) {
  // adapt canvas
  // canvas.style = {width: canvas.width + 'px', height: canvas.height + 'px'}
  // canvas.clientHeight = canvas.height
  // canvas.clientWidth = canvas.width

  // Object.defineProperty(canvas, 'style', {
  //   get() {
  //     return {
  //       width: this.width + 'px',
  //       height: this.height + 'px'
  //     }
  //   }
  // })

  try {
    Object.defineProperty(canvas, 'clientHeight', {
      get() {
        return this.height
      }
    })

    Object.defineProperty(canvas, 'clientWidth', {
      get() {
        return this.width
      }
    })
  }catch (e){
    // 客户端对象无法劫持报错，但是最终还是可以设置上去，所以吞掉错误
  }

  // 重新将客户端注入的对象实例进行强制复写
  copyProperties(canvas, EventTarget.prototype)

  // eslint-disable-next-line
  const document = {
    createElementNS(_, type) {
      if (type === 'canvas') return canvas
      if (type === 'img') {
        const img = canvas.createImage()
        img._typeofImage = true;
        copyProperties(img, EventTarget.prototype)

        return img
      }
    }
  }
  copyProperties(document.constructor.prototype, EventTarget.prototype)

  // eslint-disable-next-line
  const window = {
    AudioContext: function() {},
    URL: {},
  }
  copyProperties(window.constructor.prototype, EventTarget.prototype)

  // eslint-disable-next-line
  const atob = (a) => {
    return _atob(a)
  }

  // eslint-disable-next-line
  const XMLHttpRequest = _XMLHttpRequest

  const exports = {};

  // eslint-disable-next-line
  const HTMLCanvasElement = undefined;

  // three.js source code will be injected here
  // eslint-disable-next-line
  '__INJECT_THREE__'

  return exports
}

