using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MLEM.Extended.Tiled;
using MLEM.Extensions;
using MLEM.Misc;
using MLEM.Textures;

namespace GreatSpringGameJam {
    public class SnowBlowerWind : Entity {

        private readonly Vector2 velocity;
        private TimeSpan timeToLive;

        public SnowBlowerWind(Map map, Vector2 position, Vector2 velocity) : base(map, position) {
            this.velocity = velocity;
            this.timeToLive = TimeSpan.FromSeconds(0.25F);
        }

        public override void Update(GameTime time) {
            base.Update(time);
            this.Position += this.velocity;
            this.timeToLive -= time.ElapsedGameTime;
            if (this.timeToLive <= TimeSpan.Zero) {
                this.Map.RemoveEntity(this);
            } else {
                var (x, y) = this.Position.ToPoint();
                var tile = this.Map.GetTile("Snow", x, y);
                if (!tile.IsBlank) {
                    var tilesetTile = this.Map.GetTilesetTile(tile, this.Map.GetTileset(tile));
                    // check if the wind actually intersects with the snow's collision box
                    if (tilesetTile.Objects.Any(o => this.Map.GetArea(o, new Vector2(x, y)).Contains(this.Position))) {
                        if (tilesetTile.Properties.GetBool("SnowBottom"))
                            y--;
                        for (var yOff = 0; yOff <= 1; yOff++) {
                            this.Map.SetTile("Snow", x, y + yOff, 0);
                            var hidden = this.Map.GetTile("SnowHidden", x, y + yOff);
                            if (!hidden.IsBlank) {
                                this.Map.SetTile("Ground", x, y + yOff, hidden.GlobalIdentifier);
                                this.Map.SetTile("SnowHidden", x, y + yOff, 0);
                            }
                            this.Map.RemoveEntity(this);
                        }
                    }
                }
            }
        }

        public override void Draw(GameTime time, SpriteBatch batch) {
            base.Draw(time, batch);
            var tex = StuffTexture[1, 0];
            batch.Draw(tex, this.Position * this.Map.TileSize - tex.Size.ToVector2() / 2, Color.White);
        }

    }
}