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

[CustomPropertyDrawer(typeof(ColorSelect))]
public class ColorSelectDrawer : PropertyDrawer {

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

		#if UNITY_EDITOR_WIN
		float platformOffset =  96f/Screen.dpi;
		#endif

		#if UNITY_EDITOR_OSX
		float platformOffset =  72f/Screen.dpi;
		#endif

		ColorSelect cs = attribute as ColorSelect;

		SerializedProperty colorTotal = property.serializedObject.FindProperty (cs.totalColors);
		SerializedProperty colorArray = property.serializedObject.FindProperty (cs.colorArray);
		SerializedProperty textureArray = property.serializedObject.FindProperty (cs.textureArray);

		if (!colorArray.isArray) {
			return;
		}

		Rect[] rectHolder = new Rect[colorTotal.intValue + 1];

		for (int r = 0; r < colorTotal.intValue + 1; r++) {
			if (r == 0) {
				rectHolder [r] = new Rect (position.x, position.y, position.width, (position.height - 8f) / ((float)colorTotal.intValue + 1));
			} else {
				rectHolder [r] = new Rect (position.x, rectHolder [r - 1].yMax + 2f, position.width, (position.height - 8f) / ((float)colorTotal.intValue + 1));
			}
		}
		if (Selection.objects.Length != 1) {
			return;
		}


		if (cs.totalColors != "" || Selection.objects.Length == 1) {
			if (colorTotal.intValue > 0) {
				GUI.Label (rectHolder [0], "Object Textures & Colors");
				for (int i = 0; i < colorArray.arraySize; i++) {

					Rect tempRect = new Rect (rectHolder [i + 1].x, rectHolder [i + 1].y, rectHolder [i + 1].height, rectHolder [i + 1].height);
					Rect bigRect = new Rect (tempRect.x, tempRect.y, tempRect.width+8, tempRect.height+8);
					Rect smallRect = new Rect (tempRect.x, tempRect.y, tempRect.width-8, tempRect.height-8);
					GUIContent tempContent = new GUIContent ("         Color " + (i + 1).ToString ());

					GUI.Label (tempRect, (Texture)textureArray.GetArrayElementAtIndex (i).objectReferenceValue);
					colorArray.GetArrayElementAtIndex (i).colorValue = EditorGUI.ColorField (rectHolder [i + 1], tempContent, colorArray.GetArrayElementAtIndex (i).colorValue, true, false, false);
					textureArray.GetArrayElementAtIndex (i).objectReferenceValue = (Texture)EditorGUI.ObjectField (tempRect, (Texture)textureArray.GetArrayElementAtIndex (i).objectReferenceValue, typeof(Texture), true);
					//GUI.Box (tempRect, (Texture)textureArray.GetArrayElementAtIndex (i).objectReferenceValue);
				}
			}
		}
	}

	public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
		ColorSelect cs = attribute as ColorSelect;

		SerializedProperty colorTotal = property.serializedObject.FindProperty (cs.totalColors);

		if (Selection.objects.Length != 1) {
			return base.GetPropertyHeight (property, label);
		}

		return ((base.GetPropertyHeight (property, label) + 2f) * ((float)colorTotal.intValue + 1f)) + 8f;
	}
}