using System;
using Turbo.Plugins.Default;
 
namespace Turbo.Plugins.User
{
    public class DAV_WallPlugin : BasePlugin, IInGameWorldPainter {
        public double WallWidth { get; set; } = 1.5d;
        public double WallLength { get; set; } = 18d;
        public IBrush WallBrush { get; set; }
        
        private double toRad { get; set; } = Math.PI / 180d;
 
        public DAV_WallPlugin() {
            Enabled = true;
        }
 
        public override void Load(IController hud) {
            base.Load(hud);
 
            WallBrush = Hud.Render.CreateBrush(255, 51, 255, 51, 2);
        }
 
        public void PaintWorld(WorldLayer layer) {
            foreach (var actor in Hud.Game.Actors) {
                if (actor.SnoActor.Sno == ActorSnoEnum._monsteraffix_waller_model)
                    DrawWall(WallBrush, actor.FloorCoordinate, Direction(actor));
            }
        }
 
        private float Direction(IActor actor) {
            var diffX = (double) (actor.FloorCoordinate.X - actor.CollisionCoordinate.X);
            var diffY = (double) (actor.FloorCoordinate.Y - actor.CollisionCoordinate.Y);
 
            if (diffX == 0 && diffY == 0)
                return -45f;
 
            return (float) (Math.Atan2(diffY, diffX) / toRad) - 45f;
        }
 
        private void DrawWall(IBrush cBrush, IWorldCoordinate worldCoord, float rotation) {
            if (cBrush == null) return;
 
            var radius = ((float) Math.Sqrt(WallLength * WallLength + WallWidth * WallWidth)) * 0.5f;
            if (radius <= 0f) return;
 
            var revAngle = rotation * toRad + Math.Atan2(WallWidth, WallLength);
            var revX = radius * (float)Math.Cos(revAngle);
            var revY = radius * (float)Math.Sin(revAngle);
            var wCoord_1 = worldCoord.Offset(revX, revY, 0);
            var wCoord_3 = worldCoord.Offset(-revX, -revY, 0);
 
            revAngle = rotation * toRad - Math.Atan2(WallWidth, WallLength);
            revX = radius * (float)Math.Cos(revAngle);
            revY = radius * (float)Math.Sin(revAngle);
            var wCoord_2 = worldCoord.Offset(revX, revY, 0);
            var wCoord_4 = worldCoord.Offset(-revX, -revY, 0);
 
            cBrush.DrawLineWorld(wCoord_1, wCoord_2);
            cBrush.DrawLineWorld(wCoord_2, wCoord_3);
            cBrush.DrawLineWorld(wCoord_3, wCoord_4);
            cBrush.DrawLineWorld(wCoord_4, wCoord_1);
        }
    }
}