using System;
using Assets.Source.CommonWorkers;
using Assets.Source.General;
using Assets.Source.Patterns.ObjectPool;
using Assets.Source.Utils;
using UnityEngine;
using Object = UnityEngine.Object;

public static class CustomExtensions
{
    public static T Spawn<T>(this T prefab, Vector3 pos, Quaternion rotation) where T : MonoBehaviour, IPoolObject
    {
        if (PoolManager.Instance != null && PoolManager.AwakeDone)
            return PoolManager.Instance.Spawn(prefab, pos, rotation);

        return Instantiator.Instantiate(prefab, pos, rotation);
    }
    public static T Spawn<T>(this T prefab, Vector3 pos, Vector3 rotation) where T : MonoBehaviour, IPoolObject
    {
        return Spawn(prefab, pos, Quaternion.Euler(rotation));
    }
    public static T Spawn<T>(this T prefab, Vector3 pos) where T : MonoBehaviour, IPoolObject
    {
        return Spawn(prefab, pos, Quaternion.identity);
    }
    public static T Spawn<T>(this T prefab) where T : MonoBehaviour, IPoolObject
    {
        return Spawn(prefab, Vector3.zero, Quaternion.identity);
    }

    public static void Release(this IPoolObject obj)
    {
        if (PoolManager.Instance != null && PoolManager.AwakeDone)
            PoolManager.Instance.Release(obj);
        if (!Application.isPlaying)
            Object.DestroyImmediate(obj.gameObject);
    }

    public static void AddOnReleaseHandler(this IPoolObject obj, Action<IPoolObject> action)
    {
        if (!PoolManager.HasInstance)
            return;
        PoolManager.Instance.AddReleaseHandler(obj, action);
    }

    public static void Attach(this Transform t, AttachedObject args)
    {
        args.ThisTransform = t;
        Get.Worker<WorkerTransformAttachment>().AttachTransform(args);
    }

    public static void Attach(this Transform t, Transform target, Vector3 offset, bool unattachOnDisable = true)
    {
        Get.Worker<WorkerTransformAttachment>().AttachTransform(t, target, offset, unattachOnDisable);
    }

    public static void Attach(this Transform t, Transform target, bool unattachOnDisable = true)
    {
        Get.Worker<WorkerTransformAttachment>().AttachTransform(t, target, Vector3.zero, unattachOnDisable);
    }

    public static void Unattach(this Transform t)
    {
        Get.Worker<WorkerTransformAttachment>().UnattachTransform(t);
    }
}
