using UnityEngine;

public class MainCamera : MonoBehaviour
{

    private static MainCamera instance;

    public static MainCamera Instance
    {
        get
        {
            return instance;
        }
    }

    public int boundary = 10;

    public int pixelInUnit = 80;

    public CameraLimits worldLimits;

    public float moveSpeed = 5;

    private Camera mainCamera;

    void Awake()
    {
        instance = this;
    }

    void Start()
    {
        mainCamera = GetComponent<Camera>();
        mainCamera.orthographicSize = Screen.height / pixelInUnit / 2;
    }

    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0) // back
        {
            Camera.main.orthographicSize = Mathf.Max(Camera.main.orthographicSize - 1, 3);
        }
        else if (Input.GetAxis("Mouse ScrollWheel") < 0) // forward
        {
            Camera.main.orthographicSize = Mathf.Min(Camera.main.orthographicSize + 1, 6);
        }

        float h = Input.GetAxis("Horizontal") * moveSpeed;
        float v = Input.GetAxis("Vertical") * moveSpeed;

        if (Input.mousePosition.x <= boundary)
            h -= moveSpeed;
        else if (Input.mousePosition.x >= Screen.width - boundary)
            h += moveSpeed;
        if (Input.mousePosition.y <= boundary)
            v -= moveSpeed;
        else if (Input.mousePosition.y >= Screen.height - boundary)
            v += moveSpeed;

        SetPosition(transform.localPosition.x + h, transform.localPosition.y + v);
    }

    private void SetPosition(Vector2 pos)
    {
        SetPosition(pos.x, pos.y);
    }

    private void SetPosition(float x, float y)
    {
        float fact = mainCamera.orthographicSize / 3;

        transform.localPosition = new Vector3(
            Mathf.Max(worldLimits.X0 + mainCamera.pixelWidth / 2 / pixelInUnit * fact, Mathf.Min(worldLimits.X1 - mainCamera.pixelWidth / 2 / pixelInUnit * fact, x)),
            Mathf.Max(worldLimits.Y0 + mainCamera.pixelHeight / 2 / pixelInUnit * fact, Mathf.Min(worldLimits.Y1 - mainCamera.pixelHeight / 2 / pixelInUnit * fact, y)),
            transform.localPosition.z
        );
    }

}
