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

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

// UI_Request에서 함수 호출 버튼 클릭 시, 결과값을 보여주는 UI
public class UI_ResultUI : MonoBehaviour {
    
    [SerializeField] private RectTransform resultTextParent;
    [SerializeField] private TMP_InputField resultText;
    [SerializeField] private Button resultUICloseButton;

    private RectTransform _resultRectTransform;

    public void Initialize() {
        resultUICloseButton.onClick.AddListener(() => gameObject.SetActive(false));
        
        _resultRectTransform = resultText.GetComponent<RectTransform>();
    }
    
    public void OpenResultUI(string resultString) {
        resultString = $"{UIManager.Instance.MainFunctionName} - {UIManager.Instance.SubFunctionName}\n" + resultString;
        Reset();
        gameObject.SetActive(true);
        Debug.Log(resultString);
        resultText.text = resultString;
    }

    void Update() {
        // resultText는 ContentSizeFitter로 글자 수만큼 길이가 늘어난다.
        // 그러나 위 코드와 같이 대입한다고 해서 바로 늘어나는 것이 아닌,
        // 어느정도 크기를 측정할 시간이 필요하다.
        // 그래서 시간이 조금 지난 후에야 width, height를 측정할 수 있도록 코루틴을 통해 대기 시간을 준다.
        if (resultTextParent.rect.height != _resultRectTransform.rect.height) {
            resultTextParent.offsetMax = new Vector2(0, 0);
            resultTextParent.offsetMin = new Vector2(0, -_resultRectTransform.rect.height);
        }
    }

    // 크기를 원래대로 지정한다
    public void Reset() {
        resultTextParent.offsetMax = new Vector2(0, 0);
        resultTextParent.offsetMin = new Vector2(0, 0);
        resultText.text = string.Empty;
    }
}