using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UniRx.Triggers;
using UniRx;
public class Map : MonoBehaviour
{
    public float MapSpeed;

    public MapElement MapPrefab;
    public Vector2 RoadShift = new Vector2(60, 20);
    public List<Vector2> BackgroundsShift = new List<Vector2>()
    {
        new Vector2(60,20),
        new Vector2(0,30),
        new Vector2(60,0)
    };
    public Vector2 ShiftPoint;
    public GameObject MapContainer;

    static readonly object padlock = new object();
    static Map instance;
    public Collider2D MapEnd;
    public static Map Instance
    {
        get
        {
            if (instance == null)
                lock (padlock)
                    if (instance == null)
                        instance = FindObjectOfType<Map>();
            return instance;
        }
    }

    private void Start()
    {
        MapContainer = this.gameObject;
        provider = GetComponent<MapElementsProvider>();
        MapEnd.OnTriggerEnter2DAsObservable().Where(x => x.HasComponent<MapChunk>()).Subscribe(x =>
          {
              var chunk = x.GetComponent<MapChunk>();
              chunk.MapEndedRaise();
              provider.MPool.Return(chunk);
          }).AddTo(this);
    }
    MapElementsProvider provider;

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        foreach (var item in BackgroundsShift)
        {
            Gizmos.DrawCube(item + MapContainer.transform.position.ToVector2(), new Vector3(2, 2));
        }
        Gizmos.color = Color.green;
        Gizmos.DrawCube(RoadShift + MapContainer.transform.position.ToVector2(), new Vector3(2, 2));
        Gizmos.color = Color.magenta;
        Gizmos.DrawCube(ShiftPoint + MapContainer.transform.position.ToVector2(), new Vector3(2, 2));

    }
    int lastID;
    public void DrawNext()
    {
        var map = provider.MPool.Rent();
        map.transform.parent = MapContainer.transform;
        map.GetComponent<MapMoving>().MapSpeed = MapSpeed;
        map.transform.localPosition = RoadShift.ToVector3();
        map.GetComponent<MapChunk>().MapSpawned();

        map.GetComponent<MapChunk>().ID = lastID;
        lastID++;
    }





    void SpawnRoad()
    {

    }

}
