using System.Linq;

public sealed class ShipEquipment
{

    public readonly EquipmentSlot Ship;
    public readonly EquipmentSlot Drive;
    public readonly EquipmentSlot Tank;
    public readonly EquipmentSlot CargoModule;
    public readonly EquipmentSlot Shield;
    public readonly EquipmentSlot Weapon;

    public readonly EquipmentSlot[] AllEquipment;

    private static readonly EquipmentBlueprintParams defaultEquiment = new EquipmentBlueprintParams() { Id = "none" };

    public int FuelCapacity => CountParam("fuel");
    public int Damage => CountParam("damage");

    public int JumpRadius => CountParam("range");

    public int CargoSpace => CountParam("cargo");

    public int Armor => CountParam("armor");

    public int PowerShield => CountParam("shield");

    public ShipEquipment(
        int shipId, int driveId, int tankId, int cargoModuleId, int shieldId, int weaponId,
        EquipmentBlueptints eqipment)
    {
        Ship = new EquipmentSlot(shipId, eqipment.Ships.GetOrDefault(shipId, defaultEquiment));
        Drive = new EquipmentSlot(driveId, eqipment.Drives.GetOrDefault(driveId, defaultEquiment));
        Tank = new EquipmentSlot(tankId, eqipment.Tanks.GetOrDefault(tankId, defaultEquiment));
        CargoModule = new EquipmentSlot(cargoModuleId, eqipment.CargoModules.GetOrDefault(cargoModuleId, defaultEquiment));
        Shield = new EquipmentSlot(shieldId, eqipment.Shields.GetOrDefault(shieldId, defaultEquiment));
        Weapon = new EquipmentSlot(weaponId, eqipment.Weapons.GetOrDefault(weaponId, defaultEquiment));

        AllEquipment = new EquipmentSlot[] {
            Ship,
            Drive,
            Tank,
            CargoModule,
            Shield,
            Weapon
        };
    }

    public int CountParam(string paramId) {
        var sum = 0;
        foreach (var equip in AllEquipment)
        {
            if (equip.Blueprint.Params == null)
                continue;
            sum += equip.Blueprint.Params.Where(param => param.Key == paramId).Sum(param => param.Value);
        }
        return sum;
    }

    public int SetEquip(Type type, int id, EquipmentBlueprintParams blueprint) {
        var equipId = (int)type;
        var sellCost = AllEquipment[equipId].Blueprint.SellCost;
        AllEquipment[equipId].Set(id, blueprint);
        return sellCost;
    }

    public enum Type
    {
        Ship = 0,
        Drive = 1,
        Tank = 2,
        CargoModule = 3,
        Shield = 4,
        Weapon = 5
    }
}
