using UnityEngine;

namespace Cryville.Crtr {
	public class MeshWrapper {
		public GameObject MeshObject {
			get;
			private set;
		}
		public MeshFilter MeshFilter {
			get;
			private set;
		}
		public Mesh Mesh {
			get { return MeshFilter.mesh; }
			set { MeshFilter.mesh = value; }
		}
		public Transform MeshTransform {
			get;
			private set;
		}
		public Renderer Renderer {
			get;
			private set;
		}
		public bool Transparent {
			get;
			private set;
		}
		public bool Initialized {
			get;
			private set;
		}
		public Material NewMaterial {
			get {
				return Material.Instantiate(GenericResources.Materials[
					Transparent ? "-TransparentMat" : "-CutoutMat"
				]);
			}
		}
		public void Init(Transform parent, bool transparent = false) {
			Transparent = transparent;
			MeshObject = new GameObject("__mesh__");
			MeshTransform = MeshObject.transform;
			MeshTransform.SetParent(parent, false);
			if (MeshObject.GetComponent<MeshFilter>() == null)
				MeshObject.AddComponent<MeshFilter>();
			if (MeshObject.GetComponent<MeshRenderer>() == null)
				MeshObject.AddComponent<MeshRenderer>();
			MeshFilter = MeshObject.GetComponent<MeshFilter>();
			Renderer = MeshObject.GetComponent<Renderer>();
			Renderer.material = GenericResources.Materials[
				transparent ? "-TransparentMat" : "-CutoutMat"
			]; // TODO
			Initialized = true;
		}
		public void Destroy() {
			Mesh.Destroy(Mesh);
			if (Renderer.material != null) Material.Destroy(Renderer.material);
			GameObject.Destroy(MeshObject);
		}
	}
}
