import Deferred from './Deferred'

let __sdk = null
let __doc = null
let __mount_list = []

const deferred = Deferred()

export const sdk = deferred.promise()
export const sdk_mounted = (cb) => {
  __mount_list.push(cb)
  if (__sdk) {
    cb(__sdk)
  }
}

export function setupSDK(iframe) {
  __sdk = iframe.contentWindow.__sdk
  __doc = iframe.contentDocument
  __mount_list.forEach((cb) => cb(__sdk))
  deferred.resolveValue(__sdk)
}

export function insertStyle(style) {
    __doc.body.insertAdjacentHTML('beforeend', style)
}

export function clearScreen(clear) {
  if (__doc) {
    const button = __doc.body.querySelector('.clear-screen-btn')
    if (button) {
      if (clear) {
        if (button.querySelector('i').classList.contains('icon-hide_y')) {
          button.style.visibility = 'hidden'
          button.click()
        }
      } else {
        button.style.visibility = 'visible'
        if (button.querySelector('i').classList.contains('icon-hide_n')) {
          button.click()
        }
      }
    }
  }
}

sdk_mounted(()=>{
    insertStyle(
        `<style>
            .kankan-app__split .player[name='main'] {
                width:100% !important;
            }
            .kankan-app__split .player[name='copy'] {
                display:none !important;
            }
        </style>`)
})
