﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Arugula.Animation;
using Arugula.Audio;

namespace Arugula.Games
{
    public class SBLFlourish : MonoBehaviour
    {
        public ScoreboardLabel label;
        [Header("Scaling")]
        public ValueSpring spring;
        public float positiveBump = 1.1f;
        public float negativeBump = 0.9f;
        [Header("Audio")]
        public Phonic.Options soundOptions;
        [PhonicSound] public string positiveSound;
        [PhonicSound] public string negativeSound;

        float startingScale;
        int prevValue = 0;


        private IEnumerator Start()
        {
            if (label == null) label = GetComponentInParent<ScoreboardLabel>();

            while (label.Entry == null)
                yield return null;

            prevValue = label.Entry.Value;

            label.Entry.OnUpdated += OnUpdated;
            startingScale = spring.Current = spring.goal = transform.localScale.x;
            spring.Start();
            spring.OnUpdated += Spring_OnUpdated;
        }

        private void OnUpdated(Scoreboard.Entry e)
        {
            soundOptions.position = transform.position;

            if (e.Value > prevValue)
            {
                spring.Current = startingScale * positiveBump;
                Phonic.Play(positiveSound, soundOptions);
            }
            else
            {
                spring.Current = startingScale * negativeBump;
                Phonic.Play(negativeSound, soundOptions);
            }

            prevValue = e.Value;
        }

        private void OnDisable()
        {
            spring.Stop();
        }

        private void Spring_OnUpdated(Spring spring)
        {
            transform.localScale = Vector3.one * this.spring.Current;
        }
    }
}

