using NUnit.Framework;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class PhoneManager : MonoBehaviour
{
    [SerializeField]
    private Message messageSentPrefab;

    [SerializeField]
    private Message messageReceivedPrefab;


    const float sendMessageOffsetY = -370f;
    const float receiveMessageOffsetY = -350f;
    const float maxOffsetY = 420f;

    Transform messageContainer;

    List<Message> messages = new();

    AudioSource audioSource;

    private void Start()
    {
        messageContainer = transform.GetChild(0);
        audioSource = GetComponent<AudioSource>();
    }

    public new void SendMessage(string content)
    {
        Message newMessage = Instantiate(messageSentPrefab, messageContainer);
        newMessage.SetContent(content);
        PushMessages(80);
        messages.Add(newMessage);
        newMessage.GetComponent<RectTransform>().localPosition = new Vector3(0, sendMessageOffsetY, 0);
    }

    public void ReceiveMessage(string content)
    {
        Message newMessage = Instantiate(messageReceivedPrefab, messageContainer);
        newMessage.SetContent(content);
        PushMessages(120);
        messages.Add(newMessage);
        newMessage.GetComponent<RectTransform>().localPosition = new Vector3(0, receiveMessageOffsetY, 0);
        audioSource.Play();
    }

    private void PushMessages(float offset)
    {
        foreach (Message message in messages.ToList())
        {
            RectTransform rectTransform = message.GetComponent<RectTransform>();
            rectTransform.localPosition += new Vector3(0, offset, 0);
            if (rectTransform.localPosition.y > maxOffsetY)
            {
                Destroy(message.gameObject);
                messages.Remove(message);
            }
        }
    }
}
