import { Debounce } from "@imengyu/imengyu-utils";
import { onBeforeUnmount, onMounted } from "vue";
import { useRouter } from "vue-router";

/**
 * 安卓电视焦点控制帮助类
 * @param fromApp 是否从应用启动
 * @returns 
 */
export function useTvFocusImprovement(fromApp = false) {
  
  const router = useRouter()
  if (fromApp) {
    router.afterEach( (to, from) => {
      setTimeout(() => {
        focusFirstElement();
      }, 1000);
    });
  }

  function focusFirstElement() {
    const focusableElements = getFocusableElement();
    if (focusableElements.length) {
      for (const element of focusableElements) {
        if (element.classList.contains('active')) {//优先激活选中条目
          element.focus();
          return;
        }
      }
      focusableElements[0].focus();
    }
  }
  function getFocusableElement() {
    return document.querySelectorAll<
      | HTMLButtonElement
      | HTMLAnchorElement
      | HTMLInputElement
      | HTMLSelectElement
      | HTMLTextAreaElement
    >(
      'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
  }

  const backDebounce = new Debounce(1000, () => router.back());

  function handleKeyUp(e: KeyboardEvent) {
    if (e.key === 'Enter') {
      if (document.activeElement)
        (document.activeElement as HTMLElement).click();
    } else if (e.key === 'Backspace') {
      handleBackButton();
    }
  }
  function handleBackButton() {
    if (router.currentRoute.value.name === 'Home')
      plus.runtime.quit();
    else
      backDebounce.execute();
  }

  
  if (fromApp) {
    if(window.plus) {
      plusReady();  
    } else {
      document.addEventListener("plusready", plusReady, false);  
    }  
    // 扩展API准备完成后要执行的操作  
    function plusReady(){ 
      console.log('plusReady!');
      plus.key.addEventListener("backbutton", handleBackButton);
    }  

    onMounted(() => {
      window.addEventListener('keyup', handleKeyUp);
      setTimeout(() => {
        focusFirstElement();
      }, 2000);
    })
    onBeforeUnmount(() => {
      window.removeEventListener('keyup', handleKeyUp);
    });
  }

  return {
    focusFirstElement,
    getFocusableElement,
  }
}
