<script lang="ts">
  //import { onMount } from "lifecycle";
  import { beforeUpdate, afterUpdate } from 'svelte';
  import * as Three from 'three';

//#region variables
  let innerWidth: number = 0;
  let innerHeight: number = 0;
  let maxInnerWidth: number = 0;
  let maxInnerHeight: number = 0;

  let portrait: boolean = true;
  let focalLength: number = (540/Math.atan(70*Math.PI / 180));
  let fov = 75;
  //let baseHorizontalFOV: number = 2.0*Math.atan(baseAspectRation*Math.tan(baseVerticalFOV*0.5));
//#endregion


//#region functions
  function updateVerticalFOV(){
    fov = (180/Math.PI)*Math.tan(innerHeight/(focalLength*2));
  }


  function resetMaxDimensions(){
    maxInnerWidth = 0;
    maxInnerHeight = 0;
  }

  function updateMaxInnerDimensions(){
    if(maxInnerWidth < innerWidth){
      maxInnerWidth = innerWidth;
    }
    if(maxInnerHeight < innerHeight){
      maxInnerHeight = innerHeight;
    }
  }

  function checkOrientation(oldPortrait: boolean){
    if (innerWidth > innerHeight){
      portrait = false;
    } else {
      portrait = true;
    }

    if (oldPortrait != portrait){
      resetMaxDimensions();
    }
  }
//#endregion


  let scene: Three.Scene = new Three.Scene();
  let camera: Three.PerspectiveCamera = new Three.PerspectiveCamera(
    75,
    innerWidth / innerHeight,
    0.1,
    1000,
  );

  let renderer: Three.WebGLRenderer = new Three.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  let box: Three.BoxGeometry = new Three.BoxGeometry(1, 1, 1);
  let mat: Three.MeshBasicMaterial = new Three.MeshBasicMaterial({
    color: 0x00ff00,
  });
  let cube = new Three.Mesh(box, mat);

  scene.add(cube);

  camera.position.z = 5;
  camera.setViewOffset(
    window.innerWidth,
    window.innerHeight,
    0,
    0,
    window.innerWidth,
    window.innerHeight,
  );
  renderer.setSize(window.innerWidth, window.innerHeight);

  function animate() {
    requestAnimationFrame(animate);

    cube.rotation.x += 0.05;
    cube.rotation.y += 0.05;

    renderer.render(scene, camera);
  }
  animate();

  beforeUpdate(() => {
    checkOrientation(portrait);
    updateMaxInnerDimensions();
    updateVerticalFOV();

    camera.aspect = innerWidth / innerHeight;
    camera.fov = fov
    camera.setViewOffset(
      window.innerWidth,
      window.innerHeight,
      0,
      0,
      window.innerWidth,
      window.innerHeight,
    );
    renderer.setSize(window.innerWidth, window.innerHeight);

    //renderer.setClearColor(0x000000, (innerHeight/(maxInnerHeight))/2 + 0.5);
  });

  afterUpdate(() => {

  });
</script>

<svelte:window bind:innerWidth bind:innerHeight />

<style>
  html,
  body {
    overflow: hidden;
    padding: 0;
    margin: 0;
    position: absolute;
    width: 100%;
    height: 100%;
  }

  body {
    
  }
</style>
