using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
using YourBeatingHeart.Main.Entities;
using YourBeatingHeart.Main.States.Play.Collision;
using SFML.Window;

namespace YourBeatingHeart.Main.States.Play.Levels
{
    public class Level
    {
        private List<CollisionLine> CollisionLines;
        private DrawableEntity Sky;
        private DrawableEntity Foreground;
        private TempleBlood Blood;
        private Game Game;

        public Level(Game game)
        {
            Game = game;
            CollisionLines = new List<CollisionLine>();
        }

        // prepares level data
        public void Load(string name)
        {
            StreamReader reader = new StreamReader(Path.Combine(Constants.FOLDER_LEVELS, name + ".txt"));
            while (reader.Peek() != -1)
            {
                string lineStr = reader.ReadLine();
                if (lineStr != "")
                {
                    string[] values = lineStr.Split(',');
                    int y = int.Parse(values[0]);
                    int left = int.Parse(values[1]);
                    int right = int.Parse(values[2]);
                    CollisionLines.Add(new CollisionLine(y, left, right));
                }
            }
            
            Sky = new DrawableEntity(new Sprite(Game.LoadTexture(name + "_Sky.png")), PlayState.Layers.Sky);
            Foreground = new DrawableEntity(new Sprite(Game.LoadTexture(name + "_Foreground.png")), PlayState.Layers.LevelForeground);
            Blood = new TempleBlood(Game, new Vector2f(510, 400), name);
        }

        // configures the collision manager and shows the background
        public void Show(PlayState playState)
        {
            playState.AddEntity(Sky);
            playState.AddEntity(Foreground);

            Blood.PlayState = playState;
            playState.AddEntity(Blood);
            
            foreach (var line in CollisionLines)
            {
                playState.CollisionManager.Add(line);
            }
        }

        public void Hide(PlayState playState)
        {
            playState.RemoveEntity(Sky);
            playState.RemoveEntity(Foreground);
            playState.RemoveEntity(Blood);
        }
    }
}
