﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(Incrementor))]
public class IncrementorDrawer : PropertyDrawer {

	public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {

		Incrementor inc = attribute as Incrementor;

		Rect varLabel;
		Rect minusButton;
		Rect valueButton;
		Rect plusButton;

		string valueString = "";
		float valueFloat = 0f;


		if (GetRotationBool (property))
			valueString = GetArrayFloat (property).ToString () + "°";
		else
			valueString = GetArrayFloat (property).ToString ();

		valueFloat = GetArrayFloat (property);

		varLabel =  new Rect (position.x, position.y, Screen.width, position.height);
		minusButton = new Rect (Screen.width - (Screen.width / 2f) - 44f, position.y, Screen.width / 6f, position.height);
		valueButton = new Rect (Screen.width - (Screen.width / 3f) - 42f, position.y, Screen.width / 6f, position.height);
		plusButton = new Rect (Screen.width - (Screen.width / 6f) - 40f, position.y, Screen.width / 6f, position.height);

		GUI.Label (position, inc.floatName);
		if (GUI.Button (minusButton, "-")) {
			property.floatValue -= valueFloat;
		}
		if (GUI.Button (valueButton, valueString)) {
			inc.mySelection++;
		}
		if (GUI.Button (plusButton, "+")) {
			property.floatValue += valueFloat;
		}
	}

	private float GetArrayFloat (SerializedProperty property) {
		Incrementor inc = attribute as Incrementor;
		SerializedProperty varToCheck = property.serializedObject.FindProperty (inc.variableName);

		if (varToCheck == null)
			return 0f;

		if (varToCheck.isArray) {
			if (varToCheck.arrayElementType == "float") {
				if (varToCheck.arraySize <= 0)
					return 0f;
				
				if (varToCheck.arraySize <= inc.mySelection)
					inc.mySelection = 0;

				return varToCheck.GetArrayElementAtIndex (inc.mySelection).floatValue;
			} else {
				return 0f;
			}
		} else {
			return 0f;
		}
	}

	private bool GetRotationBool (SerializedProperty property) {
		Incrementor inc = attribute as Incrementor;
		return inc.isRotation;
	}
}
