// Copyright 2013-2022 AFI,Inc. All rights reserved

using System;
using System.Collections;
using System.Collections.Generic;
using BackEnd;
using TMPro;
using UnityEngine;
using UnityEngine.UI;



public class AlertUI : MonoBehaviour {

    [Header("스크롤 텍스트")]
    [SerializeField] private GameObject exceptionAlertUI;
    [SerializeField] private TMP_Text exceptionAlertText;
    [SerializeField] private RectTransform exceptionAlertContent;
    
    [Header("일반 텍스트")] 
    [SerializeField] private GameObject normalAlertUI;
    [SerializeField] private TMP_Text alertNormalText;

    [Header("확인 버튼")] [SerializeField] private Button confirmButton;
    private TMP_Text _confirmButtonText;

    private bool _isAlertActive = false;
    private Action _alertAction = null;

    private GameObject _mainUI;
    
    public static AlertUI Instance { get ; private set; } = null;

    
    public void Initialize() {
        if (Instance == null) {
            Instance = this;
        }

        _mainUI = transform.GetChild(0).gameObject;
        
        _confirmButtonText = confirmButton.GetComponentInChildren<TMP_Text>();
        Reset();
        
        _mainUI.SetActive(false);
    }

    
    // 비동기 작업에 대비하여 메인쓰레드로 옮긴 이후에 호출한다.
    void Update() {
        if (_isAlertActive) {
            _isAlertActive = false;
            _alertAction.Invoke();
            
            LoadingUI.Instance.CloseUI();
        }
    }
    
    public void Reset() {
        
        // 일반 알림문
        normalAlertUI.SetActive(true);
        alertNormalText.text = string.Empty;
        
        // 예외 알림문
        exceptionAlertUI.SetActive(false);
        exceptionAlertText.text = string.Empty;
        exceptionAlertContent.offsetMax = new Vector2(0, 0);
        exceptionAlertContent.offsetMin = new Vector2(0, 0);
        
        // 확인 버튼 초기화
        _confirmButtonText.text = "확인";
        confirmButton.onClick.RemoveAllListeners();
        confirmButton.onClick.AddListener( () => {
            _mainUI.SetActive(false);
        });
    }

    public void OpenUI(string alertContent) {
        _isAlertActive = true;
        _alertAction = () => {

            alertContent = $"{UIManager.Instance.MainFunctionName} - {UIManager.Instance.SubFunctionName}\n" + alertContent;
            _mainUI.SetActive(true);
            OpenNormalAlert(true);
            Debug.Log(alertContent);
            alertNormalText.text = alertContent;
        };
    }

    
    public void OpenUI(string alertContent, BackendReturnObject bro) {
        OpenUI(alertContent + "\n\n" + bro.ToString());
    }
    
    public void OpenUI(string alertContent, Exception exception) {
        _isAlertActive = true;
        _alertAction = () => {
            _mainUI.SetActive(true);

            OpenNormalAlert(false);
            exceptionAlertText.text = alertContent + "\n\n" + exception;
            StartCoroutine(ChangeAlertText());
        };
    }
    
    private void OpenNormalAlert(bool normalActive) {
        normalAlertUI.SetActive(normalActive);
        exceptionAlertUI.SetActive(!normalActive);
    }

    IEnumerator ChangeAlertText() {
        var frameUpdate = new WaitForFixedUpdate();

        for (int i = 0; i < 5; i++) {
            
            exceptionAlertContent.offsetMax = new Vector2(0, 0);
            exceptionAlertContent.offsetMin = new Vector2(0, -exceptionAlertText.rectTransform.rect.height);
            
            yield return frameUpdate;
        }
    }

    public void OpenUIWithOtherAction(string buttonName, Action action, bool alertUIClose = true) {
        _confirmButtonText.text = buttonName;

        confirmButton.onClick.AddListener(action.Invoke);
        confirmButton.onClick.AddListener(Reset);

        _mainUI.SetActive(!alertUIClose);
    }
}