using System.Linq;
using CrossCutting;
using Tesseract;

namespace InterpreterLibrary.Models
{
    public class Rectangle
    {
        public Rectangle(int x, int y, int width, int height)
        {
            X = x;
            Y = y;
            Width = width;
            Height = height;
        }

        public int X { get; set; }
        public int Y { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }

        public PointF GetTopLeft()
        {
            return new PointF(X, Y);
        }

        public PointF GetBottomRight()
        {
            return new PointF(X + Width, Y + Height);
        }

        
        public static implicit operator Rectangle(System.Drawing.Rectangle source)
        {
            return new Rectangle(source.X, source.Y, source.Width, source.Height);
        }

        public static implicit operator System.Drawing.Rectangle(Rectangle source)
        {
            return new System.Drawing.Rectangle(source.X, source.Y, source.Width, source.Height);
        }

        public static implicit operator Rectangle(Rect source)
        {
            return new Rectangle(source.X1, source.Y1, source.Width, source.Height);
        }

        public static implicit operator Rect(Rectangle source)
        {
            return new Rect(source.X, source.Y, source.Width, source.Height);
        }

        public static Rectangle FromCoords(int left, int top, int right, int bottom)
        {
            return new Rectangle(left, top, right - left, bottom - top);
        }

        public bool IntersectsWith(Rectangle otherRectangle)
        {
            var points = new[]
            {
                new Point(otherRectangle.X, otherRectangle.Y),
                new Point(otherRectangle.X + otherRectangle.Width, otherRectangle.Y),
                new Point(otherRectangle.X + otherRectangle.Width, otherRectangle.Y + otherRectangle.Height),
                new Point(otherRectangle.X + otherRectangle.Width, otherRectangle.Y)
            };
            if (points.Any(p=>
                p.X>=X 
                && p.Y>= Y
                &&  p.X < X + Width
                && p.Y < Y +Height 
                ))
            {
                return true;
            }

            var thisPoints = new[]
            {
                new Point(X, Y),
                new Point(X + Width, Y),
                new Point(X + Width, Y + Height),
                new Point(X + Width, Y)
            };
            return thisPoints.Any(p =>
                p.X >= otherRectangle.X
                && p.Y >= otherRectangle.Y
                && p.X < otherRectangle.X + otherRectangle.Width
                && p.Y < otherRectangle.Y + otherRectangle.Height
            );
        }
    }
}
