/*
 * File:			GAFClipsCreator.cs
 * Version:			1.0
 * Last changed:	2014/12/10 18:29
 * Author:			Alexey_Nikitin
 * Copyright:		© GAF Media
 * Project:			UnityVS.UnityProject.CSharp
 */

using UnityEngine;

using System.Collections;

using GAF.Assets;
using GAF.Core;

namespace GAF.Demo
{
	[AddComponentMenu("GAF/Demo/GAFClipsCreator")]
	public class GAFClipsCreator : MonoBehaviour
	{
		#region Members

		[SerializeField]
		private string BundleUrl = string.Empty;
		[SerializeField]
		private string AssetName = string.Empty;
		[Range(0, 5000)]
		[SerializeField]
		private int TimelineID = 0;
		[SerializeField]
		private bool BakeObjects = false;
		[SerializeField]
		private Vector3 Position = Vector3.zero;

		private AssetBundle m_Bundle = null;

		#endregion // Members

		#region Interface

		public GAFTexturesResource getResource(string _ResourceName)
		{
			GAFTexturesResource resource = null;

			if (m_Bundle != null)
			{
#if UNITY_5_0
				resource = m_Bundle.LoadAsset(_ResourceName, typeof(GAFTexturesResource)) as GAFTexturesResource;
#else
                resource = m_Bundle.Load(_ResourceName, typeof(GAFTexturesResource)) as GAFTexturesResource;
#endif
			}

			return resource;
		}

		#endregion // Interface

		#region Implementation

		private IEnumerator Start()
		{
			var www = WWW.LoadFromCacheOrDownload(BundleUrl, 0);

			yield return www;

			m_Bundle = www.assetBundle;

			createClip();
		}

		private void createClip()
		{
			if (m_Bundle != null)
			{
				GAFAnimationAsset asset = null;
				if (string.IsNullOrEmpty(AssetName))
					asset = m_Bundle.mainAsset as GAFAnimationAsset;
				else
#if UNITY_5_0
					asset = m_Bundle.LoadAsset(AssetName, typeof(GAFAnimationAsset)) as GAFAnimationAsset;
#else
                    asset = m_Bundle.Load(AssetName, typeof(GAFAnimationAsset)) as GAFAnimationAsset;
#endif
				var clipObj = new GameObject(asset.name);
				clipObj.transform.position = Position;
				var clip = clipObj.AddComponent<GAFMovieClip>();

				clip.initialize(asset, TimelineID, BakeObjects);
				clip.useCustomDelegate = true;
				clip.customGetResourceDelegate = getResource;
				clip.reload();
			}
		}

		#endregion // Implementation
	}
}