import Deferred from './Deferred'

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

const deferred = Deferred()

const unloadHandler = function() {
   __sdk = null
   __doc = null
}

export const sdk = deferred.promise()
export const sdk_mounted = (cb) => {
  if (__sdk) {
    cb(__sdk)
  } else {
    __mount_list.push(cb)
  }
}
export const sdk_unmounted = ()=>[
  unloadHandler()
]

export function setupSDK(iframe) {
  __sdk = iframe.contentWindow.__sdk
  __doc = iframe.contentDocument

  iframe.contentWindow.removeEventListener("unload", unloadHandler);
  iframe.contentWindow.addEventListener("unload", unloadHandler);

  let cb = null
  while((cb = __mount_list.shift()) && cb) {
    cb(__sdk)
  }
  deferred.resolveValue(__sdk)
}

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

export function clearScreen(clear,retry=0) {
  if (__doc) {
    let button = __doc.body.querySelector('.clear-screen-btn')
    if (button == void 0) {
      if(retry > 50) {
        return
      }
      return setTimeout(() => {
        clearScreen(clear,++retry)
      }, 200);
    }
    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>`
//   )
// })
