using System;
using System.Collections.Generic;
using UnityEngine;

namespace Cryville.Crtr.Components {
	public class SpriteScale3 : SpritePlane {
		public SpriteScale3() {
			SubmitProperty("border", new PropOp.Vector2(v => Border = v));
		}

		readonly static Dictionary<float, int> uvrefl
			= new Dictionary<float, int>() {
			{-0.5f, 0}, {-0.4f, 1}, {0.4f, 2}, {0.5f, 3},
		};
		static Vector2[] _origuv;
		protected new static Vector2[] OriginalUV {
			get {
				if (_origuv == null) {
					var m = GenericResources.Meshes["quad_scale3h"];
					Vector2[] uv = new Vector2[m.vertices.Length];
					for (int i = 0; i < uv.Length; i++) {
						uv[i] = new Vector2(
							uvrefl[m.vertices[i].x],
							uvrefl[m.vertices[i].z]
						);
					}
					_origuv = uv;
				}
				return _origuv;
			}
		}

		Vector2 _border = new Vector2(0, 1);
		public Vector2 Border {
			get { return _border; }
			set {
				_border = value;
				UpdateScale();
			}
		}
		protected override void UpdateScale() {
			base.UpdateScale();
			if (!mesh.Initialized) return;
			UpdateUV();
		}

		protected override void UpdateUV() {
			Vector2[] muv = OriginalUV;
			Vector2[] uv = new Vector2[muv.Length];

			var or = frameInfo.Ratio;
			var sr = Scale.x / Scale.y;
			var b = new Vector2(
				(or / sr) * _border.x,
				1 - (or / sr) * (1 - _border.y)
			);
			Vector3[] vert = mesh.Mesh.vertices;

			for (int i = 0; i < muv.Length; i++) {
				float x; float bx;
				switch ((int)muv[i].x) {
					case 0: x = 0; bx = 0; break;
					case 1: x = _border.x; bx = b.x; break;
					case 2: x = _border.y; bx = b.y; break;
					case 3: x = 1; bx = 1; break;
					default: throw new Exception();
				}
				float y;
				switch ((int)muv[i].y) {
					case 0: y = 0; break;
					case 3: y = 1; break;
					default: throw new Exception();
				}
				uv[i] = frameInfo.Frame.GetUV(x, y);
				bx -= 0.5f; y -= 0.5f;
				vert[i] = new Vector3(bx, 0, y);
			}
			mesh.Mesh.uv = uv;
			mesh.Mesh.vertices = vert;
		}
		
		public override void Init() {
			frameInfo.Load();
			InternalInit("quad_scale3h");
			OnFrameUpdate();
		}
	}
}
