using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;

public class DayCycle : MonoBehaviour
{

	[Tooltip("Number of minutes per second that pass, try 60 = 1 minute every second")]
	public float minutesPerSecond;
    public int DaysPerSeason = 1;
    public Material TreeMaterial;
    public Material GrassMaterial;
    public List<Color> GroundSeasonColors;
    public GameObject SnowParticles;
    public GameObject RainParticles;
    public int CurrentSeason = 0;
    public int SeasonCount = 4;

    public delegate void NewDay();
    public static event NewDay OnNewDay;

    public delegate void NewSeason(Seasons season);
    public static event NewSeason OnNewSeason;

	private Quaternion directionalLightRotation;
	private Light directionalLight;
	private float time;
	private float timeAlt;
    float daysPassed = 0;
    bool hasSeasonChanged = true;



	// Use this for initialization
	void Start()
	{
		directionalLightRotation = transform.rotation;
		directionalLight = GetComponent<Light>();
        ChangeSeason(true);
	}

	// Update is called once per frame
	void Update()
	{
		float angleThisFrame = Time.deltaTime / 360 * minutesPerSecond;
		transform.RotateAround(transform.position, Vector3.forward, angleThisFrame);
		if (transform.eulerAngles.z > 110f && transform.eulerAngles.z < 310f)
		{
			timeAlt = 0;
			time += 0.5f * Time.deltaTime;
			directionalLight.intensity = Mathf.Lerp(1, 0, time);
            hasSeasonChanged = false;
		}
		else if (transform.eulerAngles.z >= 310f)
		{
			time = 0;
            timeAlt += 0.5f * Time.deltaTime;
			directionalLight.intensity = Mathf.Lerp(0, 1, timeAlt);

            
        }

        if(time == 0 && !hasSeasonChanged)
        {
            hasSeasonChanged = true;
            daysPassed++;
            if(OnNewDay != null)
            {
                OnNewDay();
            }
            if (daysPassed % DaysPerSeason == 0)
            {
                ChangeSeason();
            }
        }

	}

    public void ChangeSeason(bool forceFirstSeason = false)
    {
        Debug.Log("Season Change");
        CurrentSeason++;
        if(forceFirstSeason)
        {
            CurrentSeason = 0;
        }
        if(CurrentSeason == SeasonCount)
        {
            CurrentSeason = 0;
        }

        RainParticles.SetActive(false);
        SnowParticles.SetActive(false);

        if(OnNewSeason != null)
        {
            OnNewSeason((Seasons)CurrentSeason);
        }

        //TreeMaterial.SetTexture(0, TreeSeasonalTextures[CurrentSeason]);
        TreeMaterial.mainTextureOffset = new Vector2(0.25f * CurrentSeason, 0);
        GrassMaterial.SetColor("_Color", GroundSeasonColors[CurrentSeason]);

        if(Seasons.Winter == (Seasons)CurrentSeason)
        {
            SnowParticles.SetActive(true);
        }

        if(Seasons.Autumn == (Seasons)CurrentSeason)
        {
            RainParticles.SetActive(true);
        }
    }
}
