using Demo_Project.Service;
using Demo_Project.Shape;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Telerik.WinControls.UI;
using Telerik.Windows.Diagrams.Core;

namespace Demo_Project.Model
{
    public class ShelveModel : BaseModel
    {
        private int x;
        private int y;
        private ShelveOrientation? orientation;
        private GroupRotationService rotationService;
        public string Name { get; set; }
        public System.Drawing.Point Position
        {
            get { return new System.Drawing.Point(x, y); }
            set { x = value.X; y = value.Y; }
        }
        public ShelveOrientation Orientation
        {
            get => orientation ?? ShelveOrientation.LeftToRight;
            set => orientation = value;
        }
        public List<SpotModel> Spots { get; set; } = new List<SpotModel>();

        public override void Draw()
        {
            Shape = new RadDiagramShape()
            {
                ElementShape = new ShelveShape(),
                BackColor = Color.Gray,
                Tag = this,
                IsRotationEnabled = false,
                IsEditable = false,
                IsConnectorsManipulationEnabled = false,
                ZIndex = 1,
                Width = (Spots.Count) * (SpotShape.Width + SpotShape.WidthGap),
                Height = ShelveShape.Height,
            };
            setPostion();
            Diagram.AddShape(Shape);
            foreach (var spot in Spots)
            {
                spot.Draw();
            }
            Group();
            SetRotation(Orientation);
        }

        private void setPostion()
        {
            Shape.Position = Position;
        }

        public void SetRotation(ShelveOrientation orientation)
        {
            if (rotationService == null)
            {
                rotationService = (GroupRotationService)Diagram.ServiceLocator.GetService<IRotationService>();
            }
            rotationService.RotateGroup(GetGroupOfShelve(), orientation);
            this.orientation = orientation;
        }

        public override void ReDraw()
        {
            SetRotation(Orientation);
            setPostion();
        }

        public void Group()
        {
            var group = Diagram.Shapes.Select(x => x as RadDiagramShape).Where(x => Spots.Contains(x.Tag) || x.Tag == this).Select(x => x as IShape).ToArray();
            Diagram.Group(Name, group);
        }

        public IGroup GetGroupOfShelve()
        {
            return Diagram.Groups.FirstOrDefault(grp => grp.Name == Name);
        }

        public override void Remove()
        {
            throw new NotImplementedException();
        }

        public override void SaveChanges()
        {
            throw new NotImplementedException();
        }
    }
}
