import { makeError } from '../common.js'
import $ from 'jquery'

const _properties = new WeakMap()

function Document (option) {

  _properties.set(this, {})

  _('layouter', option && option.layouter)
  _('this', this)
  _('$this', (option && option.target) || $('<div id="canvas" class="canvas"></div>'))

  // function _pages (index) {
  //   const $layouter = _('layouter')._('$this')
  //   if (index === undefined) {
  //     const pages = new AD.Layout.Types.Collection(AD.Layout.Types.Page)
  //     $layouter.find('.page').each(() =>
  //       pages.push(this)
  //     )
  //     return pages
  //   } else {
  //     switch (typeof index) {
  //       case 'number':
  //         return $layouter.find('.page')
  //     }
  //   }
  // }

  this.state = {}
  this.header = new Header()
  this.body = {
    pages: _pages,
    layers: {},
    blocks: {},
    toJSON: function toJSON () { }
  }

  this.attachTo = function attachTo (selector) {
    if (selector === null) {
      if (_.$this !== null) {
        _.$this.remove()
        _.$this = null
      }
    } else {
      var container = selector instanceof jQuery ? selector : $(selector)
      if (container.length == 1) {
        container.append(_.$this)
        _.$this[0].adlTraget = this
        _.layouter.triggerEvent(AD.ADLEVENT_ATTACHED, container)
      } else {
        throw new ReferenceError(i18n`ERR_NO_REFERENCE_OR_MULTIPLE_REFERENCE`)
      }
    }
    return this
  }
}

function _ (a, b) {
  const property = _properties.get(this)
  if (this === window || !property) throw new ReferenceError('Access Denied or Incorrect Reference.')
  if (arguments.length === 2) {
    property[a] = b
    return this
  } else if (arguments.length === 1) {
    return property[a]
  } else {
    makeError('ERR_BAD_PARAMETERS', L`_STR_ERR_BAD_PARAMETERS`)
    return false
  }
}

Document.prototype.append = function append (a, b, c) {
  const _$this = _m.get(this).$this
  if (a instanceof AD.Page) {
    a.appendTo(_$this)
  }
}

export default Document
