//#define UIBLACKED_DEBUG
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class UIBlackedView : UIBaseView {

    [SerializeField]
    private Image blackingImage;

    [SerializeField]
    private float fadeDuration = 1;

    public UnityAction OnScreenBlacked;
    public UnityAction OnScreenCleared;

    private int fadeDirection = 0;

    public override void ShowView()
    {
#if UIBLACKED_DEBUG
        Debug.Log("[UIBlacked] Show");
#endif

        base.ShowView();
        fadeDirection = 1;
        blackingImage.raycastTarget = true;
    }

    public override void HideView()
    {
#if UIBLACKED_DEBUG
        Debug.Log("[UIBlacked] Hide");
#endif

        fadeDirection = -1;
        blackingImage.raycastTarget = true;

//        base.HideView();
    }

    private void Update ()
    {
        if (fadeDirection != 0) {
            
            if (fadeDirection > 0) {
                
                var a = blackingImage.canvasRenderer.GetAlpha();
                a += Time.deltaTime / fadeDuration;
                blackingImage.canvasRenderer.SetAlpha(Mathf.Clamp01(a));

                if (Mathf.Approximately(blackingImage.canvasRenderer.GetAlpha(), 1)) {
#if UIBLACKED_DEBUG
                    Debug.Log("[UIBlacked] Finish showing blacked");
#endif
                    fadeDirection = 0;
                    blackingImage.raycastTarget = true;
                    blackingImage.canvasRenderer.SetAlpha(1);
                    
                    if (OnScreenBlacked != null)
                        OnScreenBlacked.Invoke();
                }
                
            }

            if (fadeDirection < 0) {
                
                var a = blackingImage.canvasRenderer.GetAlpha();
                a -= Time.deltaTime / fadeDuration;
                blackingImage.canvasRenderer.SetAlpha(Mathf.Clamp01(a));

                if (Mathf.Approximately(blackingImage.canvasRenderer.GetAlpha(), 0)) {
#if UIBLACKED_DEBUG
                    Debug.Log("[UIBlacked] Finish hiding blacked");
#endif
                    fadeDirection = 0;
                    blackingImage.raycastTarget = false;
                    blackingImage.canvasRenderer.SetAlpha(0);
                    
                    if (OnScreenCleared != null)
                        OnScreenCleared.Invoke();
                }
                
            }
        }
    }
}
