import React, { memo, useContext, useEffect } from "react";
import { KrpanoRendererContext } from "../contexts";

/**
 * @see https://krpano.com/docu/xml/#view
 */
export interface ViewProps {
  /**
   * 水平视角
   * @range -180-180
   */
  hlookat?: number;
  /**
   * 垂直视角
   * @range -90-90
   */
  vlookat?: number;
  /**
   * 用户视图的广度，数值越大，视角越宽广
   */
  fov?: number;
  /**
   * 视角的最小限制
   */
  fovMin?: number;
  /**
   * 视角的最大限制
   */
  fovMax?: number;
  camRoll?: number;
  /**
   * @see https://krpano.com/docu/xml/#view.fovtype
   */
  fovType?: "VFOV" | "HFOV" | "DFOV" | "MFOV" | "SFOV";
  /**
   * 最大缩放系数，如果存在将覆盖 fovMin
   */
  maxPixelZoom?: number;
  mFovRatio?: number;
  distortion?: number;
  distortionFovLink?: number;
  stereographic?: boolean;
  pannini?: number;
  architectural?: number;
  architecturalOnlyMiddle?: boolean;
  /**
   * @see https://krpano.com/docu/xml/#view.limitview
   */
  limitView?: "off" | "auto" | "lookat" | "range" | "fullrange" | "offrange";
  /**
   * 最大向左角度
   * 需要设置 limitView=range
   * @range -180-180
   */
  hlookatMin?: number;
  /**
   * 最大向右角度
   * 需要设置 limitView=range
   * @range -180-180
   */
  hlookatMax?: number;
  /**
   * 最大向上角度
   * 需要设置 limitView=range
   * @range -90-90
   */
  vlookatMin?: number;
  /**
   * 最大向下角度
   * 需要设置 limitView=range
   * @range -90-90
   */
  vlookatMax?: number;
  rx?: number;
  ry?: number;
  tx?: number;
  ty?: number;
  tz?: number;
  ox?: number;
  oy?: number;
  oz?: number;
  children?: null;
}

export const View: React.FC<ViewProps> = memo(({ children, ...viewAttrs }) => {
  const renderer = useContext(KrpanoRendererContext);

  useEffect(() => {
    if (!renderer) return;

    if (renderer.littlePlanetIntro) {
      renderer?.setTag("view", null, { ...viewAttrs });

      // TOFIX: 如果开启小行星入场，会导致 limitview 设置失效
      setTimeout(() => {
        // 等待入场动画结束覆盖属性
        renderer?.setTag("view", null, { ...viewAttrs });
      }, 4000);
    } else {
      renderer?.setTag("view", null, { ...viewAttrs }, true);
    }
  }, [renderer, viewAttrs]);

  return <div className="view">{children}</div>;
});
