using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;

public class TouchEffectManager : SingletonMonoBehaviour<TouchEffectManager> {
    [SerializeField]
    private Transform effectPrefab = default;

    private List<RaycastResult> raycastResults = new List<RaycastResult>();

    void Awake(){
        if(CheckInstance()) return ;
    }
    void Update(){
        if(Input.GetMouseButtonDown(0)){
            Camera camera = Camera.main;
            if(Camera.allCameras.Length > 1){
                float depth = -10.0f;
                foreach(Camera cam in Camera.allCameras){
                    if(depth < cam.depth){
                        depth = cam.depth;
                        camera = cam;
                    }
                }
            }
            // Cameraが取得できない時がある様なので念の為nullチェック
            if(camera == null) return ;

            EventSystem eventSystem = EventSystem.current;
            if(eventSystem != null){
                PointerEventData eventDataCurrentPosition = new PointerEventData(eventSystem);
                eventDataCurrentPosition.position = Input.mousePosition.ToVector2();
                raycastResults.Clear();
                eventSystem.RaycastAll(eventDataCurrentPosition, raycastResults);
                foreach(var result in raycastResults){
                    if(result.gameObject.name.Contains("shareButton")) return ;
                }
            }

            InstantiateEffect(camera.ScreenToWorldPoint(Input.mousePosition).SetZ(0.0f), transform);
        }
    }

    private void InstantiateEffect(Vector3 position, Transform parent){
        Instantiate(effectPrefab, position, Quaternion.identity, parent);
    }
    
    public void AllDestroyEffects(){
        foreach(Transform child in transform){
            if(child.name.Contains(effectPrefab.name)){
                Destroy(child.gameObject);
            }
        }
    }
}
