﻿using UnityEditor;
using UnityEngine;
using UnityEngine.Animations;

public class ConstrainArmature : MonoBehaviour
{
#if UNITY_EDITOR
	static Transform find_child(Transform[] transforms, string name){
		foreach(Transform t in transforms){
			if(t.name == name) return t;
		}
		return null;
	}

    [MenuItem("ClothingTool/Parent Constrain Armatures")]
    static void ParentConstrainArmatures()
    {
        GameObject master;
		GameObject slave;
		
		if(Selection.gameObjects[0].name.Contains("Clothes")){
			master = Selection.gameObjects[1];
			slave = Selection.gameObjects[0];
		}else if(Selection.gameObjects[1].name.Contains("Clothes")){
			master = Selection.gameObjects[0];
			slave = Selection.gameObjects[1];
		}else{
			Debug.LogError("At least one of the objects must contain 'Clothes' in the name!", Selection.gameObjects[0]);
			return;
		}
		
		Transform[]  slave_transforms =  slave.transform.GetComponentsInChildren<Transform>();
		Transform[] master_transforms = master.transform.GetComponentsInChildren<Transform>();
		
		foreach(Transform slave_transform in slave_transforms){;
			Transform master_transform = find_child(master_transforms, slave_transform.name);
			if(master_transform == null){
				Debug.Log("Could not find " + slave_transform.name + "!");
				continue;
			}
			
			ParentConstraint constraint = slave_transform.gameObject.AddComponent<ParentConstraint>();
			
			ConstraintSource constraintSource = new ConstraintSource();
			constraintSource.sourceTransform = master_transform;
			constraintSource.weight = 1.0F;
			constraint.AddSource(constraintSource);
			
			constraint.locked = true;
			
			constraint.weight = 1.0F;
			constraint.constraintActive = true;
		}
    }

    [MenuItem("ClothingTool/Parent Constrain Armatures", true)]
    static bool ValidateParentConstrainArmatures()
    {
        return Selection.gameObjects.Length == 2;
    }
#endif
}