import gurobipy as gu
import numpy as np
from mip import Model, xsum, maximize, BINARY, MINIMIZE, MAXIMIZE, INTEGER


all_rezy = []

def odpad(plan_rezu, delka):
    return delka - np.sum(plan_rezu)


def posli(rez, useky, delka):
    """
    delka = 200
    useky = [80, 50, 30]
    """
    for usek in useky:
        if len(rez) == 0 or rez[-1] >= usek:
            kandidat = rez.copy()
            kandidat.append(usek)
            if odpad(kandidat, delka) >= 0:

                if odpad(kandidat, delka) < 30:
                    all_rezy.append(kandidat)
                # print(kandidat)
                posli(kandidat, useky, delka)


if __name__ == "__main__":

    delka = 200
    # useky = [80, 50, 30]
    # potrebujeme = [120, 310, 150]


    useky = [80, 50, 30]
    potrebujeme = [120, 310, 150]


    posli([], useky, delka)
    print("--------------")
    irange = range(len(useky))
    plan_ji = []
    odpad_j = []
    for rez in all_rezy:
        # if np.sum(rez) + useky[-1] >= delka:
        column = [rez.count(useky[i]) for i in irange]
        odpad = delka - np.sum(rez)
        # if odpad <= 10:
        plan_ji.append(column)
        odpad_j.append(odpad)
            # print(rez, np.sum(rez), column, odpad)

    jrange = range(len(odpad_j))
    plan_ij = np.transpose(np.array(plan_ji))
    odpad_j = np.array(odpad_j)


    print(np.shape(plan_ij))
    print(plan_ij)
    print(odpad_j)

    m = Model("plan", sense=MINIMIZE, solver_name="CBC")
    x_j = [m.add_var(var_type=INTEGER) for j in jrange]

    # m.update()
    for i in irange:
        # m.addConstr(gu.quicksum(plan_ij[i, j]*x_j[j] for j in jrange) >= potrebujeme[i])
        m += xsum(plan_ij[i, j]*x_j[j] for j in jrange) == potrebujeme[i]

    m.objective = xsum(x_j[j] for j in jrange)
    m.verbose = 0
    m.optimize()

    for j in jrange:
        print(x_j[j].x, ": ", plan_ij[:, j])

    print(m.objective_value)

    print()
    print(plan_ij)
        #if x_j[j].x >= 0.3:
        #    print(x_j[j].x, ": ", plan_ij[:, j])
