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

[RequireComponent(typeof(RopeSim))]
public class RopeKidRenderer : MonoBehaviour {
    public GameObject KidRopePrefab;
    private List<GameObject> kids = new List<GameObject>();
    private RopeSim ropesim;
    void Start () {
        ropesim = GetComponent<RopeSim>();
        if ( !ropesim.sane ) {
            return;
        }
        foreach( GameObject kid in kids ) {
            Destroy(kid);
        }
        kids.Clear();
        for ( int i=1;i<ropesim.bones.Count-1;i+=2 ) {
            GameObject kid = Instantiate(KidRopePrefab);
            kid.transform.SetParent( ropesim.bones[i-1] );
            kid.transform.localPosition = Vector3.zero;
            kid.transform.up = ropesim.bones[i-1].up;
            kids.Add(kid);
            SkinnedMeshRenderer mesh = kid.GetComponentInChildren<SkinnedMeshRenderer>(kid);
            List<Transform> bones = new List<Transform>();
            bones.Add( ropesim.bones[i-1] );
            bones.Add( ropesim.bones[i] );
            bones.Add( ropesim.bones[i+1] );
            mesh.bones = bones.ToArray();
            mesh.localBounds = new Bounds(Vector3.zero, new Vector3(5,5,5));
        }
    }

    void Update() {
        if ( kids.Count != Mathf.Ceil((ropesim.bones.Count-2f)/2f) ) {
            Start();
            return;
        }
        bool powered = false;
        foreach( GameObject obj in ropesim.end.GetComponent<RopeAttachPoint>().GetConnections() ) {
            if ( obj.GetComponent<Generator>() != null ) {
                powered = true;
                break;
            }
        }
        if ( powered ) {
            for ( int i=0;i<kids.Count;i++ ) {
                SkinnedMeshRenderer mesh = kids[i].GetComponentInChildren<SkinnedMeshRenderer>();
                mesh.SetBlendShapeWeight(0, Mathf.Sin(-Time.time*5f+i)*100f);
            }
            for ( int i=0;i<ropesim.bones.Count;i++ ) {
                float scale = 1f+((Mathf.Sin(-Time.time*5f+(i/3f))+1f)*0.2f);
                ropesim.bones[i].localScale = new Vector3( scale, scale, scale );
            }
            ropesim.noise = 0.2f;
        } else {
            ropesim.noise = 0.08f;
        }
    }
}
