using UnityEngine;
using UnityStandardAssets.ImageEffects;

public class Sun : MonoBehaviour {

    public static float timeToFade = 3f;

    public static float waitBeforeDying = 26f;

    private const float fps = 30;

    private static Color originalColor = Color.white;

    private static Light myLight = null;

    private static Sun instance = null;

    private static float startingFade = 0f;

    private static bool isFading = false;

    private static Material nightSkybox = null;

    private static VignetteAndChromaticAberration vignetteCamera = null;

    void Start () {
        if (instance != null) {
            Debug.LogError("Error : only one instance of Sun must be running at a time !");
            return;
        }
        instance = this;
        myLight = GetComponent<Light>();
        originalColor = myLight.color;
        nightSkybox = Resources.Load<Material>("Materials/Night 01A");
        vignetteCamera = Camera.main.GetComponent<VignetteAndChromaticAberration>();
    }

    void Update() {
        if (Bed.mustSleep) {
            if (vignetteCamera.intensity < 1) {
                vignetteCamera.intensity = PlayerBehaviour.timeBeforeDyingAtNight / (PlayerBehaviour.timeBeforeDyingAtNight - (Time.time - startingFade) / 1.5f) - 1;
            } else if (vignetteCamera.intensity > 1) {
                vignetteCamera.intensity = 1;
            }
        }
    }

    void ReloadLevel() {
        Application.LoadLevel(Application.loadedLevel);
    }

    public static void FadeToNight() {
        if (!isFading) {
            isFading = true;
            startingFade = Time.time;
            instance.Invoke("ReloadLevel", waitBeforeDying + 2 * Retry.fadeDuration + Retry.fadeDuration);
            Bed.mustSleep = true;
            Camera.main.GetComponent<Skybox>().material = nightSkybox;
            RotateSkybox.skyboxMat = nightSkybox;
            SoundManager.ChangeMusicSmooth("night");
            instance.InvokeRepeating("FadeNight", 0, 1 / fps);
        }
    }

    void FadeNight() {
        Color currentColor = myLight.color;
        myLight.color = new Color(Mathf.Clamp(currentColor.r - 1 / (timeToFade * fps), 0, 1), Mathf.Clamp(currentColor.g - 1 / (timeToFade * fps), 0, 1), Mathf.Clamp(currentColor.b - 1 / (timeToFade * fps), 0, 1));
        if (Time.time - startingFade > timeToFade) {
            myLight.color = Color.black;
            isFading = false;
            CancelInvoke("FadeColor");
        }
    }

	public static void SetColor(Color c) {
        myLight.color = c;
    }

    public static void ResetColor() {
        myLight.color = originalColor;
    }
}