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

public class uScrollViewMgr : MonoBehaviour
{
    public ScrollRect m_ScrollRect;
    public GameObject m_Content;
    public GameObject go_card;

    protected List<CardBase> list_CardBase = new List<CardBase>();
    protected RectTransform contentRt;

    protected CardBase m_SelectCard;

    void Awake()
    {
        Init();
    }

    protected virtual void Init()
    {
        if (DSUtil.CheckNull(contentRt))
        {
            if (m_ScrollRect)
                contentRt = m_ScrollRect.content;
            else if (m_Content)
                contentRt = m_Content.GetComponent<RectTransform>();
        }
    }

    protected void CardBase_AllOff()
    {
        for (int i = 0; i < list_CardBase.Count; i++)
            list_CardBase[i].gameObject.SetActive(false);
    }

    CardBase MakeCard(int i)
    {
        CardBase temp;
        if (list_CardBase.Count > i) temp = list_CardBase[i];
        else
        {
            temp = DSUtil.Get_Clone<CardBase>(go_card, contentRt);
            list_CardBase.Add(temp);
        }
        return temp;
    }

    protected virtual void Set_ScrollView<T>(List<T> _lst, int idata = -1)
    {
        Init();
        CardBase_AllOff();

        for (int i = 0; i < _lst.Count; i++)
            MakeCard(i).Set(_lst[i], i, idata);
    }
    protected virtual void Set_ScrollView_NotSet(int _makecount)
    {
        Init();
        for (int i = 0; i < _makecount; i++)
        {
            if (list_CardBase.Count > i) { }
            else list_CardBase.Add(DSUtil.Get_Clone<CardBase>(go_card, contentRt));
        }
        CardBase_AllOff();
    }

    protected void ScrollTo_XY(Transform target)
    {
        Canvas.ForceUpdateCanvases();
        contentRt.anchoredPosition = (Vector2)m_ScrollRect.transform.InverseTransformPoint(contentRt.position) - (Vector2)m_ScrollRect.transform.InverseTransformPoint(target.position);
    }
    protected void ScrollTo(Transform target, bool vertical)
    {
        Canvas.ForceUpdateCanvases();
        Vector2 offset = (Vector2)m_ScrollRect.transform.InverseTransformPoint(contentRt.position) - (Vector2)m_ScrollRect.transform.InverseTransformPoint(target.position);
        Vector2 anchor = contentRt.anchoredPosition;
        if (vertical) anchor.y = offset.y - target.GetComponent<RectTransform>().sizeDelta.y;
        else anchor.x = offset.x - target.GetComponent<RectTransform>().sizeDelta.x;
        contentRt.anchoredPosition = anchor;
    }
}