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

public class CustomEventIllustration : MonoBehaviour {

    private float squeezeValue;

    [SerializeField]
    private float speedSqueeze = 6f;

    [SerializeField]
    private float speedColorChange = 0.5f;

    [SerializeField]
    private float amount = 0.15f;

    [SerializeField]
    private Material materialToChange;

    bool animationEnabled = false;

    // Animate the iX logo scale in X direction
    void SqueezeObject()
    {
        squeezeValue = 1 + (amount*Mathf.Sin(Time.time * speedSqueeze));
        gameObject.transform.localScale = new Vector3(gameObject.transform.localScale.y * squeezeValue, gameObject.transform.localScale.y, gameObject.transform.localScale.z);
    }

    // Change the color of the caps on the iX logo
    void ChangeColor()
    {
        float r = squeezeValue = (1 + (Mathf.Sin((Time.time * speedColorChange) + 1 * (2 * Mathf.PI / 3))))/2;
        float g = squeezeValue = (1 + (Mathf.Sin((Time.time * speedColorChange) + 2 * (2 * Mathf.PI / 3))))/2;
        float b = squeezeValue = (1 + (Mathf.Sin((Time.time * speedColorChange) + 3 * (2 * Mathf.PI / 3))))/2;
        Color col = new Color(r, g, b);
        SetEmissionColorOfShader(col, materialToChange.shader);
    }

    public void SetEmissionColorOfShader(Color col, Shader targetShader)
    {
        // Get all MeshRenderer components from child objects
        MeshRenderer[] meshRendererInChildren = transform.GetComponentsInChildren<MeshRenderer>();

        // for each MeshRenderer get the applied materials and change its emission color
        foreach (MeshRenderer meshRendererChild in meshRendererInChildren)
        {
            Material[] mats = meshRendererChild.materials;
            foreach (Material mat in mats)
            {
                if (mat.shader == targetShader)
                {

                    mat.SetColor("_EmissionColor", col);
                }
            }
        }
    }

    // If animation is running stop it. Otherwise the animation will be started
    public void ToggleColorAnimation()
    {
        animationEnabled = !animationEnabled;
    }

    public void SetActiveAnimation(bool state)
    {
        animationEnabled = state;
    }

    // Update is called once per frame
    void Update () {
        if (animationEnabled)
        {
            SqueezeObject();
            ChangeColor();
        }
    }
}
