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

public enum GuideType 
{
    Rect,
    Circle
}

[RequireComponent(typeof(CircleGuide))]
[RequireComponent(typeof(RectGuide))]
public class GuideController : MonoBehaviour , ICanvasRaycastFilter
{
    private CircleGuide circleGuide;
    private RectGuide rectGuide;

    public Material rectMat;
    public Material circleMat;

    private Image mask;

    private RectTransform target;

    public Canvas canvas;

    private Image img;

    public static GuideController Instance;
    private void Awake()
    {
        Instance = this;

        mask = transform.GetComponent<Image>();
        img = transform.GetComponentInChildren<Image>(true);

        if ( mask == null ) { throw new System.Exception("mask 初始化失败!"); }
        if ( img == null) { throw new System.Exception("img 初始化失败!"); }

        if (rectMat == null || circleMat == null) { throw new System.Exception("材质未赋值!"); }

        circleGuide = transform.GetComponent<CircleGuide>();
        rectGuide = transform.GetComponent<RectGuide>();
    }


    public void Guide(RectTransform target, GuideType guideType)
    {
        this.target = target;
        gameObject.SetActive(true);

        switch (guideType)
        {
            case GuideType.Rect:
                mask.material = rectMat;
                rectGuide.Guide(canvas, target);
                break;
            case GuideType.Circle:
                mask.material = circleMat;
                circleGuide.Guide(canvas, target);
                break;
        }
    }

    public void Guide(Vector2 Pos,Vector2 Size) 
    {
        target = img.rectTransform;

        img.rectTransform.anchoredPosition = Pos;
        img.rectTransform.sizeDelta = Size;

        mask.material = rectMat;
        rectGuide.Guide(canvas, img.rectTransform);
    }

    public void Guide(Vector2 Pos,float Radius)
    {
        target = img.rectTransform;

        img.rectTransform.anchoredPosition = Pos;
        mask.material = circleMat;
        circleGuide.Guide(canvas, img.rectTransform);
    }
    public void Full()
    {
        gameObject.SetActive(true);
        mask.material = rectMat;
        mask.material.SetFloat("_SliderX", 0);
        mask.material.SetFloat("_SliderY", 0);
    }

    public void Clear() 
    {
        gameObject.SetActive(false);
    }

    public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        if (target == null) { return false; } // 事件不会渗透

        return !RectTransformUtility.RectangleContainsScreenPoint(target, sp, eventCamera);
    }

    private void OnApplicationQuit()
    {
        mask.material = rectMat;
        mask.material.SetFloat("_SliderX", 1500);
        mask.material.SetFloat("_SliderY", 1500);
    }
}
