import { BoardViewerPage } from './board-viewer-page'

function serialize(obj) {
  var str = [] as string[]
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
    }
  return str.join('&')
}

function readFileAsync(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader()

    reader.onload = () => {
      resolve(reader.result)
    }

    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

export class PrintableBoardViewerPage extends BoardViewerPage {
  get context() {
    return {
      ...super.context,
      printable: {
        accept: ['preview'],
        content: async () => {
          const image = await this.fetchImage()
          await this.printTrick(image)

          return this as any
        }
      }
    }
  }

  async fetchImage() {
    const modelId = this._boardId
    const data = {
      title: this.context.title
    }
    const queryString = serialize(data)
    const url = `${location.origin}/screenshot/${modelId}${queryString ? '?' + queryString : ''}`

    const response = await fetch(url)
    return await readFileAsync(await response.blob())
  }
}

customElements.define('printable-board-viewer-page', PrintableBoardViewerPage)
