using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Serialization;

public class ScriptedDialogueTrigger : MonoBehaviour
{
    [Serializable]
    private enum Speaker
    {
        Radio,
        Baz
    }
    
    [SerializeField] private DialogueSystem _dialogue;
    
    [SerializeField] private Speaker _speaker = Speaker.Radio;
    [SerializeField] private Transform _speakerTransform;
    [Obsolete]
    [SerializeField] private string _key;

    [SerializeField] private string[] _keys;
    private float[] _durations;

    [SerializeField]
    private UnityEvent _onDialogueFinish;

    [SerializeField] private bool _log;

    private void Awake()
    {
        if (_keys.Length == 0) return;
        
        _durations = new float[_keys.Length];
        for (int i = 0; i < _keys.Length; i++)
        {
            _durations[i] = _dialogue.GetLineDuration(_keys[i]);

            if (_speaker == Speaker.Radio)
            {
                // fudge because radio has a bit of a delay before starting the clip
                _durations[i] += 0.3f;
            }
        }
    }

    private void OnTriggerEnter( Collider other )
    {
        if ( !other.CompareTag( "Player" ) )
            return;
        
        Trigger(other.ToString() );
    }
    
    public void Trigger( string name = "[UNKNOWN]" ) {
        if ( _log )
        {
            Debug.Log($"{name} triggered dialogue {_key}");
        }

        if (_keys.Length == 0)
        {
            PlayLine(_key, _speakerTransform);
        }
        else
        {
            StartCoroutine(PlayKeys());
        }
    }

    private IEnumerator PlayKeys()
    {
        var idx = 0;
        var elapsed = 0f;

        // play first line
        PlayLine(_keys[0], _speakerTransform);
        
        while (idx < _keys.Length)
        {
            elapsed += Time.deltaTime;
            if (elapsed > _durations[idx])
            {
                elapsed = 0;
                
                idx++;
                
                if (idx >= _keys.Length) break;
                
                PlayLine(_keys[idx], _speakerTransform);
            }

            yield return null;
        }
        
        _onDialogueFinish.Invoke();
    }

    private void PlayLine(string key, Transform speakerObject)
    {
        switch (_speaker)
        {
            case Speaker.Radio:
                _dialogue.PlayLineRadio(key);
                break;
            
            case Speaker.Baz:
                _dialogue.PlayLineBaz(key, speakerObject);
                break;
        }
    }
}
