using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class Phone : MonoBehaviour
{
    public static Phone Instance;

    public GameObject on;
    public GameObject off;

    private float time_until_call;
    public float mtt_call = 20f;
    public float call_time_var = 5f;

    private float timeUntilNotification;
    private float notificationTime;
    public float mttNotification = 12f;
    public float notificationTimeVar = 8f;
    
    public Monitor monitor;
    private AudioSource ringingAudio;
    public AudioClip notificationSound;
    
    private bool ringing;
    public bool screenOn;

    private void Awake()
    {
        Instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        Light.contributions.Add(gameObject, 0);
        ringingAudio = GetComponentInChildren<AudioSource>();
        
        reset();
    }

    public void reset()
    {
        resetCall();
        timeUntilNotification = Random.Range(mttNotification - notificationTimeVar,
            mttNotification + notificationTimeVar);
        notificationTime = 0;
    }

    public void resetCall()
    {
        time_until_call = Random.Range(mtt_call - call_time_var, mtt_call + call_time_var);
    }

    // Update is called once per frame
    void Update()
    {
        time_until_call -= Time.deltaTime;
        timeUntilNotification -= Time.deltaTime;
        notificationTime -= Time.deltaTime;
        
        if (time_until_call <= 0f)
        {
            if (!ringing)
            {
                ringingAudio.Play();
            }
            
            ringing = true;
        }
        else
        {
            ringingAudio.Stop();
            ringing = false;
        }
        
        
        screenOn = time_until_call <= 3f;

        if (timeUntilNotification <= 0f)
        {
            timeUntilNotification = Random.Range(mttNotification - notificationTimeVar,
                mttNotification + notificationTimeVar);

            if (!screenOn)
            {
                AudioManager.playClip(notificationSound);
                notificationTime = 1f;
                time_until_call += 4f;
                SleepDepth.subtract(.2f);

                if (monitor.gameObject.activeInHierarchy)
                {
                    monitor.switchOn();
                }
            }
        }

        bool b = screenOn || notificationTime > 0;
        
        on.SetActive(b);
        off.SetActive(!b);

        Light.contributions[gameObject] = b ? 0.1f : 0;

        if (ringing)
        {
            SleepDepth.drainInSecs(4f);
        }
    }
}
