import { Debounce } from "@imengyu/imengyu-utils";
import { onBeforeUnmount, onMounted } from "vue";
import { useRouter } from "vue-router";
import SpatialNavigation from 'spatial-navigation-js';

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

  function initSpatialNavigation() {
    SpatialNavigation.add({
      selector: '.focusable, a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
    });
    // Make the *currently existing* navigable elements focusable.
    SpatialNavigation.makeFocusable();
    // Focus the first navigable element.
    SpatialNavigation.focus();
  }

  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(initSpatialNavigation, 2000);
    })
    onBeforeUnmount(() => {
      window.removeEventListener('keyup', handleKeyUp);
    });
  }
}
