using UnityEngine;
using System.Collections;
using System;
public class MouseDragSelect : MonoBehaviour
{
    private Rect position = new Rect(193, 148, 249 - 193, 148 - 104);
    public Color color = Color.green;
    private Vector3[] mousePositions = new Vector3[2];
    private bool draggingMouse = false;
    private bool drawRect = false;
    public float timer = 0.7f;
    void OnGUI()
    {
        if (drawRect)
        {
            DrawRectangle(position, 1, color);
        }
    }
    void DrawRectangle(Rect area, int frameWidth, Color color)
    {
        //Create a one pixel texture with the right color
        var texture = new Texture2D(1, 1);
        texture.SetPixel(0, 0, color);
        texture.Apply();
        Rect lineArea = area;
        lineArea.height = frameWidth; //Top line
        GUI.DrawTexture(lineArea, texture);
        lineArea.y = area.yMax - frameWidth; //Bottom
        GUI.DrawTexture(lineArea, texture);
        lineArea = area;
        lineArea.width = frameWidth; //Left
        GUI.DrawTexture(lineArea, texture);
        lineArea.x = area.xMax - frameWidth;//Right
        GUI.DrawTexture(lineArea, texture);
    }
    void reset()
    {
        drawRect = false;
        mousePositions[0] = new Vector3();
        mousePositions[1] = new Vector3();
        timer = 0.7f;
        draggingMouse = false;
    }
    private void Update()
    {
        if (drawRect)
        {
            if (timer > 0.1)
            {
                timer -= 1 * Time.deltaTime;
            }
            else
            {
                reset();
            }
        }
        if (Input.GetMouseButtonDown(0))
        {
            if (!draggingMouse)
            {
                mousePositions[0] = Input.mousePosition;
                Debug.Log("x start:" + mousePositions[0].x);
                Debug.Log("y start:" + mousePositions[0].y);
            }
            draggingMouse = true;
        }
        if (Input.GetMouseButtonUp(0))
        {
            if (draggingMouse)
            {
                mousePositions[1] = Input.mousePosition;
                float width = Math.Abs(mousePositions[1].x - mousePositions[0].x);
                float height = Math.Abs(mousePositions[1].y - mousePositions[0].y);
                float x = mousePositions[0].x;
                float y = mousePositions[0].y;
                // Debug.Log("width:" + width);
                // Debug.Log("height:" + height);
                Debug.Log("x end:" + mousePositions[1].x);
                Debug.Log("y end:" + mousePositions[1].y);
                position = new Rect(x, y, width, height);
                // Debug.Log("Got last mouse position!");
                drawRect = true;
            }
        }
    }
}