using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameCameraState : BaseCameraState {

    private float startFov;
    private float targetFov = 20;

    public Transform objectToFollow;

    private Vector3 startPosition;
    private Vector3 targetPosition;
    private Vector3 cameraOffset = new Vector3(12, 12, 12);
    private Vector3 offsetForce = new Vector3(-4, 0, -4);

    private Vector3 startDir;

    private float startTime;
    private float transitionDuration = 2;

    public override void InitState()
    {
        base.InitState();

        this.startTime = Time.time;
        this.startPosition = this.gameController.CameraController.MainCamera.transform.position;
        this.startDir = this.gameController.CameraController.MainCamera.transform.forward;
        this.startFov = this.gameController.CameraController.MainCamera.fieldOfView;

    }

    public override void UpdateState()
    {
        base.UpdateState();

        this.targetPosition = this.objectToFollow.position + this.cameraOffset;
        var targetDirection = (this.objectToFollow.position - this.targetPosition).normalized;

        if (Time.time - this.startTime < transitionDuration) {
            var trans = (Time.time - this.startTime) / transitionDuration;

            var newCamPos = new Vector3 (Mathfx.Hermite(this.startPosition.x, this.targetPosition.x, trans),
                Mathfx.Hermite(this.startPosition.y, this.targetPosition.y, trans),
                Mathfx.Hermite(this.startPosition.z, this.targetPosition.z, trans));
            
            this.gameController.CameraController.MainCamera.transform.position = newCamPos;

            this.gameController.CameraController.MainCamera.fieldOfView = Mathfx.Hermite(this.startFov, this.targetFov, trans);

            var newCamDir = new Vector3 (Mathfx.Hermite(this.startDir.x, targetDirection.x, trans),
                Mathfx.Hermite(this.startDir.y, targetDirection.y, trans),
                Mathfx.Hermite(this.startDir.z, targetDirection.z, trans));
            this.cameraController.MainCamera.transform.forward = newCamDir;    

        } else {
            
            Vector3 mousePosition = new Vector3(Input.mousePosition.x - Screen.width/2, 0, Input.mousePosition.y - Screen.height/2);
            mousePosition = Vector3.Scale(mousePosition, new Vector3(1.0f/Screen.width, 0, 1.0f/Screen.height));
            mousePosition = Vector3.Scale(mousePosition, offsetForce);
            mousePosition = Quaternion.Euler(0, 45, 0) * mousePosition;
            
            this.gameController.CameraController.MainCamera.transform.position = this.targetPosition + mousePosition;

            this.cameraController.MainCamera.transform.forward = targetDirection;
        }
    }

    public override void DeinitState()
    {
        this.gameController.CameraController.MainCamera.fieldOfView = this.startFov;

        base.DeinitState();
    }
}
