﻿using UnityEngine;
using System.Collections.Generic;
using MCS;
using MCS.FOUNDATIONS;
using MCS.COSTUMING;

namespace RogoDigital.Lipsync.Extensions {
	public class MCSBlendSystem : BlendSystem {

		/// <summary>
		/// The MCS Character.
		/// </summary>
		public MCSCharacterManager mcsCharacter;
		public bool detachMorphsWhenNotUsed = false;

		[SerializeField, HideInInspector]
		private List<string> blendshapes;

		// Do any setup necessary here. BlendSystems run in edit mode as well as play mode, so this will also be called when Unity starts or your scripts recompile.
		// Make sure you call base.OnEnable() here for expected behaviour.
		public override void OnEnable () {
			base.OnEnable();

			// Sets info about this blend system for use in the editor.
			blendableDisplayName = "Morph";
			blendableDisplayNamePlural = "Morphs";
			noBlendablesMessage = "Your chosen MCS Character has no Morphs defined.";
			notReadyMessage = "MCS Character not set. The MCS BlendSystem requires an MCS Character.";
		}

		public override void SetBlendableValue (int blendable, float value) {
			if (!isReady) return;
			SetInternalValue(blendable, value);
            mcsCharacter.SetBlendshapeValue(blendshapes[blendable], value);
		}

		public override string[] GetBlendables () {
			if (!isReady) return new string[0];
			if (!mcsCharacter.coreMorphs) return new string[0];

			List<string> shapes = new List<string>();
			blendshapes = new List<string>();
			ClearBlendables();

            mcsCharacter.coreMorphs.SortIfNeeded();
			for (int i = 0; i < mcsCharacter.coreMorphs.morphs.Count; i++) {
				blendshapes.Add(mcsCharacter.coreMorphs.morphs[i].name);
				AddBlendable(i, mcsCharacter.coreMorphs.morphs[i].value);
				shapes.Add(string.Format("{0} ({1})", mcsCharacter.coreMorphs.morphs[i].name, i));
			}

			return shapes.ToArray();
		}

		public override void OnBlendableAddedToPose (int blendable) {
			if (!isReady) return;
            mcsCharacter.coreMorphs.AttachMorphs(new string[] { blendshapes[blendable] });
		}

		public override void OnBlendableRemovedFromPose (int blendable) {
			if (!isReady) return;
			if (detachMorphsWhenNotUsed) mcsCharacter.coreMorphs.DettachMorphs(new string[] { blendshapes[blendable] });
		}

		public override void OnVariableChanged () {
			if (mcsCharacter != null) {
				isReady = true;
			} else {
				isReady = false;
			}
		}
	}
}