/*
 * File:			GAFLoadResourceFromBundle.cs
 * Version:			1.0
 * Last changed:	2014/12/4 16:46
 * Author:			Alexey_Nikitin
 * Copyright:		© GAF Media
 * Project:			UnityVS.UnityProject.CSharp
 */

using UnityEngine;

using System.Collections;

using GAF.Core;
using GAF.Assets;

namespace GAF.Demo
{
	[AddComponentMenu("GAF/Demo/GAFLoadResourceFromBundle")]
	[RequireComponent(typeof(GAFMovieClip))]
	public class GAFLoadResourceFromBundle : 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;

		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;

			setUpClip();
		}

		private void setUpClip()
		{
			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 clip = GetComponent<GAFMovieClip>();

				clip.initialize(asset, TimelineID, BakeObjects);
				clip.usePlaceholder = false;
				clip.reload();

				clip.setDefaultSequence(true);
			}
		}

		#endregion // Implementation
	}
}
