/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.UI.Lite.Controls
{
	using System;
	using Fusion.Graphics;

	public class Spinner : ITimeProcessor
	{
		private Image _image;
		private IPlane _plane;
		private IVisual _visual;
		private bool _active;

		public Spinner(Image image)
		{
			if (image == null)
				throw new ArgumentNullException(nameof(image));
			
			_image = image;
		}

		public Image Image
		{
			get
			{
				return _image;
			}
		}

		public void Layout()
		{
			if (_plane != null)
			{
				float width = _image.Width / _image.PixelsPerPoint;
				float height = _image.Height / _image.PixelsPerPoint;

				float x = (_plane.Width - width) / 2F;
				float y = (_plane.Height - height) / 2F;

				_visual.SetBounds(x, y, width, height);
				_visual.Update();
			}
		}

		public void Attach(IPlane plane)
		{
			if (_plane == null)
			{
				_plane = plane;

				_visual = _plane.AddVisual();

				Layout();

				_visual.Drawing = new ImageDrawing(_image);
				_visual.Invalidate();
			}
		}

		public void Detach()
		{
			if (_plane != null)
			{
				_visual.Remove();

				_visual = null;

				_plane = null;
			}
		}

		public void Start()
		{
			if (!_active)
			{
				VisualUpdater.AddProcessor(this);

				_active = true;
			}
		}

		public void Stop()
		{
			if (_active)
			{
				VisualUpdater.RemoveProcessor(this);

				_active = false;
			}
		}

		public virtual void Process(float dt)
		{
			if (_active)
			{
				_visual.Angle += 10F;

				if (_visual.Angle > 360F)
					_visual.Angle -= 360F;

				_visual.Update();
			}
		}
	}
}