// zig fmt: off
const std = @import("std");
const Store = @import("../store.zig");
const json_utils = @import("../json_utils.zig");

const DropRate = @This();

item: Store.Id,
rate: u64,
min_quantity: u64,
max_quantity: u64,

pub fn parse(store: *Store, obj: std.json.ObjectMap) !DropRate {
    const rate = try json_utils.getIntegerRequired(obj, "rate");
    if (rate < 1) {
        return error.InvalidRate;
    }

    const min_quantity = try json_utils.getIntegerRequired(obj, "min_quantity");
    if (min_quantity < 1) {
        return error.InvalidMinQuantity;
    }

    const max_quantity = try json_utils.getIntegerRequired(obj, "max_quantity");
    if (max_quantity < 1) {
        return error.InvalidMinQuantity;
    }

    const code = try json_utils.getStringRequired(obj, "code");
    const item_id = try store.items.getOrReserveId(code);

    return DropRate{
        .item = item_id,
        .rate = @intCast(rate),
        .min_quantity = @intCast(min_quantity),
        .max_quantity = @intCast(max_quantity)
    };
}

pub fn parseDrops(store: *Store, array: std.json.Array, drops: []DropRate) !usize {
    for (0.., array.items) |i, drop_value| {
        const drop_obj = json_utils.asObject(drop_value) orelse return error.InvalidObject;

        if (i >= drops.len) {
            return error.Overflow;
        }

        drops[i] = try DropRate.parse(store, drop_obj);
    }

    return array.items.len;
}
