using System.Collections.Generic;
using GGJ.Models;
using GGJ.Objects;
using UnityEngine;

namespace GGJ
{
    public class Level : MonoBehaviour
    {
        public LightDestination destination;
        public List<LightSource> sources;
        public List<Block> blocks;
        public List<BaseDraggable> items;
        public List<Sprite> tutorials;

        public int[,] grid = new int[7, 5]
        {
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0}
        };

        private float horizontalStart;
        private float horizontalWidth;

        private float verticalStart;
        private float verticalWidth;

        public void InitGridPositions()
        {
            var p1 = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height));
            var p2 = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width / 5, 0));
            horizontalWidth = p2.x - p1.x;
            verticalWidth = horizontalWidth;
            verticalStart = p1.y;
            horizontalStart = p1.x;
            ResetGrid();
        }

        public Vector2 WorldToGrid(Vector2 w)
        {
            var x = Mathf.FloorToInt((w.x - horizontalStart) / horizontalWidth);
            var y = Mathf.FloorToInt((verticalStart - w.y) / verticalWidth);
            return new Vector2(x, y);
        }

        public void ResetGrid()
        {
            for (int i = 0; i < 7; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    grid[i, j] = 0;
                }
            }
            for (var i = 0; i < blocks.Count; i++)
            {
                var block = blocks[i];
                var gp = WorldToGrid(block.transform.localPosition);
                grid[(int) gp.y, (int) gp.x] = 1;
            }
            for (var i = 0; i < sources.Count; i++)
            {
                var source = sources[i];
                var gp = WorldToGrid(source.transform.localPosition);
                grid[(int) gp.y, (int) gp.x] = 1;
            }
            var g = WorldToGrid(destination.transform.localPosition);
            grid[(int) g.y, (int) g.x] = 1;

            for (var i = 0; i < items.Count; i++)
            {
                var draggable = items[i];
                if (!draggable.isInsideGrid) continue;
                var w = WorldToGrid(draggable.transform.localPosition);
                if (w.x >= 5 || w.y >= 7 || w.y < 0 || w.x < 0) continue;
                grid[(int) w.y, (int) w.x] = 1;
            }
        }

        public bool IsGridPositionEmpty(Vector2 w)
        {
            if (w.x >= 5 || w.y >= 7 || w.y < 0 || w.x < 0) return false;
            return grid[(int) w.y, (int) w.x] == 0;
        }

    }
}