using RobotNet.RobotShares.Models;
using RobotNet.Script;
using RobotNet.Script.Expressions;

namespace RobotNet.ScriptManager.Helpers;

public static class VDA5050ScriptHelper
{
    public static RobotState ConvertToRobotState(RobotStateModel model)
    {
        bool isReady = model.IsOnline && !model.OrderState.IsProcessing && model.Errors.Length == 0;
        if(model.ActionStates.Length > 0)
        {
            isReady = isReady && model.ActionStates.All(a => !a.IsProcessing);
        }
        return new RobotState(isReady, model.BatteryState.BatteryVoltage, model.Loads.Length != 0, model.BatteryState.Charging, model.AgvPosition.X, model.AgvPosition.Y, model.AgvPosition.Theta);
    }

    public static RobotInstantActionModel ConvertToRobotInstantActionModel(string robotId, RobotAction action)
    {
        return new RobotInstantActionModel
        {
            RobotId = robotId,
            Action = new RobotShares.VDA5050.InstantAction.Action
            {
                ActionType = action.ActionType,
                BlockingType = action.BlockingType switch
                {
                    BlockingType.NONE => "NONE",
                    BlockingType.SOFT => "SOFT",
                    BlockingType.HARD => "HARD",
                    _ => "NONE"
                },
                ActionParameters = [..action.Parameters?.Select(p => new RobotShares.VDA5050.InstantAction.ActionParameter
                {
                    Key = p.Key,
                    Value = p.Value
                }) ?? []],
            }
        };
    }

    public static RobotShares.Models.RobotMoveToNodeModel ConvertToRobotMoveToNodeModel(string robotId, string nodeName, IDictionary<string, IEnumerable<RobotAction>> actions, double? lastAngle)
    {
        return new RobotShares.Models.RobotMoveToNodeModel
        {
            RobotId = robotId,
            NodeName = nodeName,
            LastAngle = lastAngle ?? 0,
            OverrideLastAngle = lastAngle != null,
            Actions = actions.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Select(a => new RobotShares.VDA5050.InstantAction.Action
                {
                    ActionType = a.ActionType,
                    ActionId = Guid.NewGuid().ToString(),
                    BlockingType = a.BlockingType switch
                    {
                        BlockingType.NONE => "NONE",
                        BlockingType.SOFT => "SOFT",
                        BlockingType.HARD => "HARD",
                        _ => "NONE"
                    },
                    ActionParameters = [..a.Parameters?.Select(p => new RobotShares.VDA5050.InstantAction.ActionParameter
                    {
                        Key = p.Key,
                        Value = p.Value
                    }) ?? []],
                })
            )
        };
    }

}
