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

/// <summary>
/// Отслеживание объекта
/// </summary>
public class CameraController : MonoBehaviour
{
    public enum RotationAxes { Mouse, TrackMarker }
    public RotationAxes axes = RotationAxes.Mouse;
    public float movementSpeed = 0.1f;
    public int mouseSpeed = 100;
    public float smoothness = 0.85f;
    public Button ButtonCameraCenter;

    Vector3 targetPosition;
    private Vector3 dragOrigin;

    public Transform target;
    public GameObject location;
    
    void Start()
    {      
        targetPosition = transform.position;


        yaw = transform.eulerAngles.y;
        pitch = transform.eulerAngles.x;

        ButtonCameraCenter.onClick.AddListener(CameraCenter);
    }

    void Update()
    {
        if (!EventSystem.current.IsPointerOverGameObject())
        {
            switch (axes)
        {
            case RotationAxes.Mouse:
                //MouseCommands();

                MovementMouse();
                break;
            case RotationAxes.TrackMarker:
                TrackMarker();
                break;
        }
        }
    }  

    void ShowAndUnlockCursor()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }

    void HideAndLockCursor()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }     
   
    private void MouseCommands()
    {
        //if (Input.GetKey(KeyCode.W))
        //{
        //    targetPosition += transform.forward * movementSpeed;
        //    Camera.main.orthographicSize++;
        //}
        if (Input.GetKey(KeyCode.LeftArrow))
            targetPosition -= transform.right * movementSpeed;
        //if (Input.GetKey(KeyCode.S))
        //{
        //    targetPosition -= transform.forward * movementSpeed;
        //    if (Camera.main.orthographicSize > 1) Camera.main.orthographicSize--;
        //}
        if (Input.GetKey(KeyCode.RightArrow))
            targetPosition += transform.right * movementSpeed;
        if (Input.GetKey(KeyCode.DownArrow))
            targetPosition -= transform.up * movementSpeed;
        if (Input.GetKey(KeyCode.UpArrow))
            targetPosition += transform.up * movementSpeed;

        if (Input.GetMouseButtonDown(2))
        {
            dragOrigin = Input.mousePosition;
        }


        if (Input.GetMouseButton(1))
        {
            Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
            if (pos.x < 0)
                targetPosition -= transform.right * movementSpeed * 0.1f;
            if (pos.x > 0)
                targetPosition += transform.right * movementSpeed * 0.1f;
            if (pos.y < 0)
                targetPosition -= transform.up * movementSpeed * 0.1f;
            if (pos.y > 0)
                targetPosition += transform.up * movementSpeed * 0.1f;
        }

        if (Input.GetAxis("Mouse ScrollWheel") > 0 && !EventSystem.current.IsPointerOverGameObject())
        {
            targetPosition += transform.forward * movementSpeed* mouseSpeed;
            if (Camera.main.orthographicSize > 1) Camera.main.orthographicSize--;
        }
        else if (Input.GetAxis("Mouse ScrollWheel") < 0 && !EventSystem.current.IsPointerOverGameObject())
        {
            targetPosition -= transform.forward * movementSpeed*mouseSpeed;
            Camera.main.orthographicSize++;
        }

        transform.position = Vector3.Lerp(transform.position, targetPosition, (1.0f - smoothness));
    }

    private Vector3 screenPoint;
    private Vector3 offset;
    private Vector3 curScreenPoint;
    private Vector3 curPosition;
    void OnMouseDown()
    {
        //Debug.Log(StagesEditorController.indexCursor);
        
            screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
            offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
        
    }

    private void OnMouseDrag()
    {
        switch (axes)
        {
            case RotationAxes.Mouse:
                curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
                curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;

                transform.position = curPosition;
                break;
        }
    }    

    void TrackMarker()
    {
        transform.Translate(0, 0, Input.GetAxis("Mouse ScrollWheel") * zoomSpeed, Space.Self);

        var marker_offset = new Vector3(target.position.x, targetPosition.y, target.position.z);
        if(!target.GetComponent<Outline>().enabled) target.GetComponent<Outline>().enabled = true;
        targetPosition =Vector3.Lerp(transform.position, /*targetPosition + target.position - */marker_offset, (1.0f - smoothness));
        transform.position = targetPosition;
        if (Input.GetMouseButton(1))
        {
            target.GetComponent<Outline>().enabled = false;
            axes = RotationAxes.Mouse;

            var player = PlayerController.instance;
            if (player.UserInfo.activeSelf)
            {
                var client = Client.instance;
                client.ImageStreamStopSend(player.user_broadcast.Value);
                player.user_broadcast = null;
                player.UserInfo.SetActive(false);
            }
        }
    }


    public float lookSpeedH = 2f;
    public float lookSpeedV = 2f;
    public float zoomSpeed = 2f;
    public float dragSpeed = 1f;
    public float dragKeySpeed = 0.1f;

    private float yaw = 0f;
    private float pitch = 0f;

    void MovementMouse()
    {
        //Look around with Right Mouse
        if (Input.GetMouseButton(1))
        {
            yaw += lookSpeedH * Input.GetAxis("Mouse X");
            pitch -= lookSpeedV * Input.GetAxis("Mouse Y");

            transform.eulerAngles = new Vector3(pitch, yaw, 0f);
        }

        //drag camera around with Middle Mouse
        if (Input.GetMouseButton(2))
        {
            transform.Translate(-Input.GetAxisRaw("Mouse X") * dragSpeed, -Input.GetAxisRaw("Mouse Y") * dragSpeed, 0);
        }

        //Zoom in and out with Mouse Wheel
        transform.Translate(0, 0, Input.GetAxis("Mouse ScrollWheel") * zoomSpeed, Space.Self);

        if (Input.GetKey(KeyCode.LeftArrow))
            //targetPosition -= transform.right * movementSpeed;
            transform.Translate(-dragKeySpeed, 0, 0);
        if (Input.GetKey(KeyCode.RightArrow))
            transform.Translate(dragKeySpeed, 0, 0);
        if (Input.GetKey(KeyCode.DownArrow))
            transform.Translate(0, -dragKeySpeed, 0);
        if (Input.GetKey(KeyCode.UpArrow))
            transform.Translate(0, dragKeySpeed, 0);

    }

    public void CameraCenter()
    {
        if (location != null)
        {
            var pos = location.transform.position;
            var scale = location.transform.localScale;

            var x = pos.x - scale.x / 2;
            float y;
            var z = pos.z - scale.z / 2;
            if (x >= z)
                y = scale.x * 8;
            else y = scale.z * 8;
            transform.position = new Vector3(x, y, z);
        }
        else
            transform.position = new Vector3(5, 12, 5);
        transform.rotation = Quaternion.Euler(90, 0, 0);

        targetPosition = transform.position;
        yaw = transform.eulerAngles.y;
        pitch = transform.eulerAngles.x;
    }

}
