const std = @import("std");

const Piece = @import("piece.zig");

const Self = @This();

contents: [14]?Piece.Type,
prng: std.rand.DefaultPrng,

pub fn init() Self {

    var ret = Self{
        .contents = undefined,
        .prng = std.rand.DefaultPrng.init(@intCast(u64, std.time.milliTimestamp())),
    };
    // We must fill all of the array
    for (ret.contents[0..7]) |_, i| {
        std.debug.print("Bag: {any}\n", .{ret.contents});
        ret.contents[i] = @intToEnum(Piece.Type, i);
    }
    // Then we shuffle
    ret.prng.random().shuffle(?Piece.Type, ret.contents[0..7]);

    for (ret.contents[7..14]) |_, i| {
        std.debug.print("Bag: {any}\n", .{ret.contents});
        ret.contents[i + 7] = @intToEnum(Piece.Type, i);
    }
    // Then we shuffle
    ret.prng.random().shuffle(?Piece.Type, ret.contents[7..14]);

    return ret;
}

pub fn pop(self: *Self) Piece.Type {
    var ret = Piece.Type.i; // TODO
    if (self.contents[0]) |head| {
        ret = head;
        for (self.contents) |_, i| {
            //std.debug.print("Bag: {any}\n", .{self.contents});
            if (i + 1 >= self.contents.len) {
                break;
            }
            if (self.contents[i + 1]) |next| {
                self.contents[i] = next;
                self.contents[i + 1] = null;
            } else break;
        }
        if (self.contents[7] == null) {
            for (self.contents[7..14]) |_, i| {
                self.contents[i + 7] = @intToEnum(Piece.Type, i);
            }
        self.prng.random().shuffle(?Piece.Type, self.contents[7..14]);
        }

    }
    return ret;
}
