using System;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.UI;

public class TimeController : MonoBehaviour
{
    [Header("Inferface")]
    public TextMeshProUGUI hourText;

    public Image dayNightIcon;
    public Sprite dayIcon;
    public Sprite nightIcon;

    public PostProcessProfile profile;
    
    [Header("Others")]
    [Range(1,60)]
    public int minutesPerSecond;

    public bool day;

    public Transform skyTransform;

    public Gradient colorGradient;
    
    private DateTime hour;

    private float counter;
    
    private TimeSpan eightMorning = new TimeSpan(8, 0, 0);
    private TimeSpan tenNight = new TimeSpan(22, 0, 0);

    public bool active = false;
    
    private ColorGrading colorGradingLayer;
    
    private void Start()
    {
        profile.TryGetSettings(out colorGradingLayer);
        hour = DateTime.Now.AddYears(5);

        if (hour.TimeOfDay.CompareTo(eightMorning) >= 0 && hour.TimeOfDay.CompareTo(tenNight) < 0)
        {
            day = true;
            dayNightIcon.sprite = dayIcon;
        }
        else
        {
            day = false;
            dayNightIcon.sprite = nightIcon;
        }
        
        skyTransform.rotation = Quaternion.Euler(0,0,(GetHour() * 90) + 24);
        colorGradingLayer.enabled.value = true;
        colorGradingLayer.colorFilter.value = colorGradient.Evaluate(GetHour());
    }

    public void Activate()
    {
        active = true;
    }

    private void Update()
    {
        if (!active)
            return;
        
        counter += Time.deltaTime;

        if (counter >= 1)
        {
            counter = 0;
            hour = hour.AddMinutes(minutesPerSecond);
            SetRotation();
        }

        SetDayNight();

        
        
        hourText.text = hour.ToString("d") + "\n" + hour.ToString("t");
    }

    private float GetHour()
    {
        return Mathf.Clamp(((float) hour.Hour + ((float)hour.Minute / 60)) / 23, 0, 1);
    }
    
    private void SetRotation()
    {
        float diff = ((float)minutesPerSecond / 60) * (90f / 24);
        skyTransform.DORotate(new Vector3(0, 0, skyTransform.eulerAngles.z + diff), 1).SetEase(Ease.Linear);
    }

    private void SetDayNight()
    {
        colorGradingLayer.enabled.value = true;

        Color c = colorGradingLayer.colorFilter.value;
        DOTween.To(() => c, x => c = x, colorGradient.Evaluate(GetHour()), 1).OnUpdate(() => 
        { 
            colorGradingLayer.colorFilter.value = c;
        });
        
        
        if (hour.TimeOfDay.CompareTo(eightMorning) >= 0 && !day && hour.TimeOfDay.CompareTo(tenNight) < 0)
        {
            day = true;
            
            dayNightIcon.sprite = dayIcon;
        }
        else if (hour.TimeOfDay.CompareTo(tenNight) >= 0 && day)
        {
            day = false;
            profile.isDirty = true;
            dayNightIcon.sprite = nightIcon;
        }
    }
}
