using Cryville.Common.Math;
using Cryville.Crtr.Event;
using System;
using System.Linq;
using UnityEngine;

namespace Cryville.Crtr {
	public class GroupHandler : ContainerHandler {
		public ChartHandler ch;

		SquareMatrix matFrame;
		ContainerState[] tracks;

		public GroupHandler(Chart.Group tg, ChartHandler ch) : base() {
			this.ch = ch;
		}
		
		public override string TypeName {
			get {
				return "group";
			}
		}

		public override void PreInit() {
			base.PreInit();
			tracks = (
				from c in cs.Children
				where c.Value.Container is Chart.Track
				select c.Value
			).ToArray();
			matFrame = SquareMatrix.WithPolynomialCoefficients(tracks.Length);
			frame = new ColumnVector<Vector3>(tracks.Length);
		}

		ColumnVector<Vector3> frame;
		public ColumnVector<Vector3> GetCurrentFrame(Func<ContainerState, Vector3> func) {
			for (int i = 0; i < tracks.Length; i++)
				frame[i] = func(tracks[i]);
			return matFrame.Eliminate(frame, Vector3Operator.Instance);
		}
	}

	class Vector3Operator : IVectorOperator<Vector3> {
		public static Vector3Operator Instance = new Vector3Operator();

		public Vector3 Add(Vector3 lhs, Vector3 rhs) {
			return lhs + rhs;
		}

		public Vector3 ScalarMultiply(float lhs, Vector3 rhs) {
			return lhs * rhs;
		}
	}
}
