import React from "react"
import ReactDom from "react-dom"
import { FileUploader, FileboyProvider } from "@cd2/fileboy-react"
import { VideoPlayer } from "@cd2/fileboy-react-video"
import { insertBefore, IGlobalConfig } from "./utils"

export function setUpGlobalInputs(globalConfig: IGlobalConfig) {
  const uploaderElements = document.querySelectorAll<HTMLInputElement>("input[data-fileboy]")

  for (const uploaderElement of Array.from(uploaderElements)) {
    const rawConfig = uploaderElement.getAttribute("data-fileboy")
    const config = parseStringButtonConfig(rawConfig)
    const fileId = uploaderElement.value

    console.log(config)

    const uploaderButton = createUploadButton(globalConfig, {
      ...config,
      defaultFileId: fileId,
      onFileUploaded(file) {
        uploaderElement.value = file.id
      },
    })

    insertBefore(uploaderButton.node, uploaderElement)
  }
}

export function setUpGlobalVideoPlayers(globalConfig: IGlobalConfig) {
  const playerElements = document.querySelectorAll<HTMLInputElement>("div[data-fileboy-video]")

  for (const playerElement of Array.from(playerElements)) {
    setUpSpecificVideoPlayers(globalConfig, playerElement)
  }
}

export function setUpSpecificVideoPlayers(globalConfig: IGlobalConfig, playerElement: Element) {
  const rawConfig = playerElement.getAttribute("data-fileboy-video")
  const config = parseStringButtonConfig(rawConfig)
  const fileId = playerElement.id

  // Remove any existing children
  while (playerElement.firstChild) {
    playerElement.removeChild(playerElement.firstChild)
  }

  const videoElement = createVideoPlayer(globalConfig, {
    ...config,
    id: fileId,
  })

  // append as a child
  playerElement.appendChild(videoElement.node)
}

export function createUploadButton(
  globalConfig: IGlobalConfig,
  config: Parameters<typeof FileUploader>[0],
) {
  const uploaderContainer: Element = document.createElement("div")

  ReactDom.render(
    <FileboyProvider publicKey={globalConfig.publicKey} apiUrl={globalConfig.apiUrl}>
      <FileUploader {...config} />
    </FileboyProvider>,
    uploaderContainer,
  )

  return {
    node: uploaderContainer,
    cleanup() {
      ReactDom.unmountComponentAtNode(uploaderContainer)
    },
  }
}

export function createVideoPlayer(
  globalConfig: IGlobalConfig,
  config: Parameters<typeof VideoPlayer>[0],
) {
  const videoContainer: Element = document.createElement("div")

  ReactDom.render(
    <FileboyProvider publicKey={globalConfig.publicKey} apiUrl={globalConfig.apiUrl}>
      <VideoPlayer apiUrl={globalConfig.apiUrl} {...config} />
    </FileboyProvider>, 
    videoContainer
  )

  return {
    node: videoContainer,
    cleanup() {
      ReactDom.unmountComponentAtNode(videoContainer)
    },
  }
}

interface IUploadButtonConfig {
  uploaderStyle?: "minimal" | "buttonOnly" | "default"
  allow?: string | string[]
}
function parseStringButtonConfig(config: string | null): IUploadButtonConfig {
  if (config === null || config === "") {
    return {}
  }
  const opts = ["uploaderStyle", "allow", "height", "autoPlay", "loop"]
  const obj: any = {}
  config.split(" ").forEach(el => {
    const [key, val = true] = el.split("=")
    if (opts.includes(key)) {
      // convert string booleans to actual booleans
      obj[key] = val === "false" ? false : val === "true" ? true : val
    } else {
      console.warn(`Unrecognised data-fileboy config option "${key}"`)
    }
  })
  return obj
}
