using System;
using UnityEngine;

namespace Cryville.Crtr {
	public class SpriteFrame {
		Rect m_frame;
		public Rect Frame {
			get { return m_frame; }
			set { m_frame = value; }
		}

		bool m_rotated = false;
		public bool Rotated {
			get { return m_rotated; }
			set { m_rotated = value; }
		}

		private Rect _uv;
		private Vector2[] cuv;
		public Rect UV {
			get {
				return _uv;
			}
			private set {
				_uv = value;
				float x0 = Mathf.Min(_uv.xMin, _uv.xMax);
				float x1 = Mathf.Max(_uv.xMin, _uv.xMax);
				float y0 = Mathf.Min(_uv.yMin, _uv.yMax);
				float y1 = Mathf.Max(_uv.yMin, _uv.yMax);
				if (m_rotated) cuv = new Vector2[]{
						new Vector2(x0, y1),
						new Vector2(x1, y0),
						new Vector2(x0, y0),
						new Vector2(x1, y1),
					};
				else cuv = new Vector2[]{
						new Vector2(x0, y0),
						new Vector2(x1, y1),
						new Vector2(x1, y0),
						new Vector2(x0, y1),
					};
			}
		}
		public Vector2 GetUV(Vector2 uv) {
			return GetUV(uv.x, uv.y);
		}
		public Vector2 GetUV(float u, float v) {
			Vector2 uv00 = cuv[0], uv11 = cuv[1],
				uv10 = cuv[2], uv01 = cuv[3];
			return (1 - u - v) * uv00
				+ u * uv10
				+ v * uv01
				+ u * v * (uv00 + uv11 - uv10 - uv01);
		}
		public Texture2D Texture {
			get;
			private set;
		}
		public Vector2 Size {
			get {
				return new Vector2(Texture.width, Texture.height);
			}
		}
		public SpriteFrame(Texture2D tex) {
			if (tex == null) throw new ArgumentNullException("tex");
			Texture = tex;
			m_frame = new Rect(Vector2.zero, Size);
			var w = m_frame.width;
			var h = m_frame.height;
			float x = m_frame.x / w;
			float y = 1 - m_frame.y / h;
			float tw = (m_rotated ? m_frame.height : m_frame.width) / w;
			float th = (m_rotated ? m_frame.width : m_frame.height) / h;
			if (m_rotated) UV = new Rect(x, y, tw, -th);
			else UV = new Rect(x, y, tw, -th);
		}
	}
}
