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

public class CameraManager : MonoBehaviour
{
    public Transform cam;
    public float sensitivity;

    [Header("Main Hall")]
    public float camTransformSpeed=0.1f;
    public Transform mainHallTarget;
    private Vector3 defaultPos;
    private Quaternion defaultRot;
    public GameObject leaveHallBtn;
    public GameObject mainHallInterior;
    public bool isInsideHall => leaveHallBtn.activeSelf;

    void Update()
    {
        
    }
    
    private Vector2 mouseStartPos = Vector2.zero;
    private Vector3 cameraStartPos = Vector2.zero;
    private Vector3 mainHallCamRotationStart = Vector3.zero;
    public bool moving = false;
    public void OnMouseDown(BaseEventData e){
        PointerEventData ped = (PointerEventData) e as PointerEventData;
        mouseStartPos = ped.position;
        cameraStartPos = cam.transform.position;
        mainHallCamRotationStart = cam.transform.eulerAngles;
        moving=true;
    }
    public void OnMouseUp(BaseEventData e){
        PointerEventData ped = (PointerEventData) e as PointerEventData;
        moving=false;
    }
    public void OnMouseMove(BaseEventData e){
        PointerEventData ped = (PointerEventData) e as PointerEventData;

        Vector3 offset = (mouseStartPos-ped.position) * sensitivity;
        if(moving && !Selector.isMovingBuilding && !isInsideHall){
            cam.transform.position = cameraStartPos + new Vector3(offset.x,0,offset.y);
        }else if(isInsideHall){
            cam.eulerAngles = new Vector3(mainHallCamRotationStart.x - offset.y, mainHallCamRotationStart.y + offset.x);
        }
    }


    public void JoinMainHall(){
        Selector.insideHall=true;
        Selector.selectBuilding(null);
        leaveHallBtn.SetActive(true);
        defaultPos = cam.position;
        defaultRot = cam.rotation;
        StartCoroutine(ToggleMainHallCamera(true));
    }

    public void LeaveMainHall(){
        Selector.insideHall=false;
        leaveHallBtn.SetActive(false);
        StartCoroutine(ToggleMainHallCamera(false));
    }

    IEnumerator ToggleMainHallCamera(bool value){
        Vector3 targetPos = (value) ? mainHallTarget.position : defaultPos;
        Quaternion targetRot = (value) ? mainHallTarget.rotation : defaultRot;
        if(value){mainHallInterior.SetActive(true);}
        while(Vector3.Distance(cam.position, targetPos) > 2 || (cam.rotation * Quaternion.Inverse(targetRot)).eulerAngles.magnitude > 5){
            //Debug.Log("Current rot diff : " + (cam.rotation * Quaternion.Inverse(targetRot)).eulerAngles.magnitude);
            cam.position = Vector3.Lerp(cam.position, targetPos,camTransformSpeed);
            cam.rotation = Quaternion.Lerp(cam.rotation, targetRot, camTransformSpeed);
            yield return new WaitForEndOfFrame();
        }

        if(!value){mainHallInterior.SetActive(false);}
    }

    
}
