using System;
using UnityEngine;

namespace Cryville.Crtr.Skin.Components {
	[DisallowMultipleComponent]
	public abstract class MeshBase : SkinComponent {
		public MeshBase() {
			SubmitProperty("color", new PropOp.Color(v => Color = v));
			SubmitProperty("opacity", new PropOp.Float(v => {
				var c = Color;
				c.a *= v;
				Color = c;
			}));
			SubmitProperty("zindex", new PropOp.Integer(v => ZIndex = (short)v));
		}

		protected MeshWrapper mesh = new MeshWrapper();
		protected Material[] materials;

		short _zindex;
		public short ZIndex {
			get {
				return _zindex;
			}
			set {
				if (value < 0 || value > 5000)
					throw new ArgumentOutOfRangeException("value", "Z-index must be in [0..5000]");
				_zindex = value;
				UpdateZIndex();
			}
		}
		protected void UpdateZIndex() {
			if (!mesh.Initialized) return;
			foreach (var mat in materials) {
				mat.renderQueue = _zindex;
			}
		}

		Color _color = Color.white;
		public Color Color {
			get { return _color; }
			set {
				_color = value;
				UpdateColor();
			}
		}
		protected virtual void UpdateColor() {
			if (!mesh.Initialized) return;
			foreach (var mat in materials) {
				mat.color = _color;
			}
		}

		protected override void OnDestroy() {
			DestroyMaterials();
			mesh.Destroy();
		}

		protected void DestroyMaterials() {
			if (materials == null) return;
			foreach (var mat in materials) {
				Material.Destroy(mat);
			}
		}
	}
}
