using System;
using System.Collections.Generic;
using System.Linq;
using NavisworksTransport.Core.Models;

namespace NavisworksTransport.Core.Services
{
    /// <summary>
    /// 时标服务
    /// 整合时标的CRUD操作和计算
    /// </summary>
    public class TimeTagService
    {
        private readonly PathDatabase _database;
        private readonly TimeTagCalculator _calculator;

        public TimeTagService(PathDatabase database)
        {
            _database = database ?? throw new ArgumentNullException(nameof(database));
            _calculator = new TimeTagCalculator();
        }

        /// <summary>
        /// 为路径创建新的时标配置
        /// </summary>
        public TimeTagProfile CreateProfile(string routeId, string profileName, PathRoute route)
        {
            if (string.IsNullOrEmpty(routeId))
                throw new ArgumentException("路径ID不能为空", nameof(routeId));
            
            if (string.IsNullOrEmpty(profileName))
                throw new ArgumentException("配置名称不能为空", nameof(profileName));

            var profile = new TimeTagProfile
            {
                RouteId = routeId,
                Name = profileName,
                DefaultSpeed = Config.ConfigManager.Instance.Current.Logistics.SpeedLimitMetersPerSecond,
                TurnSpeedRatio = 0.5
            };

            // 自动生成默认事件
            profile.Events = _calculator.GenerateDefaultEvents(route);
            
            // 计算时间
            _calculator.Calculate(profile, route);
            
            // 保存到数据库
            _database.SaveTimeTagProfile(profile);
            
            LogManager.Info($"[时标服务] 创建配置: {profileName}, 事件数: {profile.Events.Count}");
            return profile;
        }

        /// <summary>
        /// 获取路径的所有时标配置
        /// </summary>
        public List<TimeTagProfile> GetProfiles(string routeId)
        {
            return _database.GetTimeTagProfiles(routeId);
        }

        /// <summary>
        /// 获取单个时标配置
        /// </summary>
        public TimeTagProfile GetProfile(string profileId)
        {
            return _database.GetTimeTagProfile(profileId);
        }

        /// <summary>
        /// 更新时标配置（并重新计算时间）
        /// </summary>
        public void UpdateProfile(TimeTagProfile profile, PathRoute route)
        {
            if (profile == null) return;

            // 重新计算时间
            _calculator.Calculate(profile, route);
            
            // 保存
            _database.SaveTimeTagProfile(profile);
        }

        /// <summary>
        /// 删除时标配置
        /// </summary>
        public void DeleteProfile(string profileId)
        {
            _database.DeleteTimeTagProfile(profileId);
        }

        /// <summary>
        /// 添加事件到配置
        /// </summary>
        public void AddEvent(TimeTagProfile profile, TimeTagEvent newEvent, PathRoute route)
        {
            if (profile?.Events == null || newEvent == null) return;

            newEvent.ProfileId = profile.Id;
            profile.Events.Add(newEvent);
            
            // 重新计算并保存
            UpdateProfile(profile, route);
        }

        /// <summary>
        /// 从配置中移除事件
        /// </summary>
        public void RemoveEvent(TimeTagProfile profile, string eventId, PathRoute route)
        {
            if (profile?.Events == null) return;

            var evt = profile.Events.FirstOrDefault(e => e.Id == eventId);
            if (evt != null)
            {
                profile.Events.Remove(evt);
                UpdateProfile(profile, route);
            }
        }

        /// <summary>
        /// 更新事件属性
        /// </summary>
        public void UpdateEvent(TimeTagProfile profile, TimeTagEvent updatedEvent, PathRoute route)
        {
            if (profile?.Events == null || updatedEvent == null) return;

            var existingEvent = profile.Events.FirstOrDefault(e => e.Id == updatedEvent.Id);
            if (existingEvent != null)
            {
                // 更新属性
                existingEvent.Name = updatedEvent.Name;
                existingEvent.Type = updatedEvent.Type;
                existingEvent.Distance = updatedEvent.Distance;
                existingEvent.WaitTime = updatedEvent.WaitTime;
                existingEvent.ActionTime = updatedEvent.ActionTime;
                existingEvent.ArriveSpeed = updatedEvent.ArriveSpeed;
                existingEvent.LeaveSpeed = updatedEvent.LeaveSpeed;

                UpdateProfile(profile, route);
            }
        }

        /// <summary>
        /// 复制时标配置
        /// </summary>
        public TimeTagProfile DuplicateProfile(TimeTagProfile source, string newName, PathRoute route)
        {
            if (source == null) return null;

            var newProfile = new TimeTagProfile
            {
                RouteId = source.RouteId,
                Name = newName,
                DefaultSpeed = source.DefaultSpeed,
                TurnSpeedRatio = source.TurnSpeedRatio
            };

            // 复制所有事件
            foreach (var evt in source.Events)
            {
                newProfile.Events.Add(new TimeTagEvent
                {
                    ProfileId = newProfile.Id,
                    PointId = evt.PointId,
                    Distance = evt.Distance,
                    Type = evt.Type,
                    Name = evt.Name,
                    WaitTime = evt.WaitTime,
                    ActionTime = evt.ActionTime,
                    ArriveSpeed = evt.ArriveSpeed,
                    LeaveSpeed = evt.LeaveSpeed
                });
            }

            // 计算并保存
            _calculator.Calculate(newProfile, route);
            _database.SaveTimeTagProfile(newProfile);

            return newProfile;
        }
    }
}
