using JuMP
using CPLEX

include("parser.jl")

start = time()

function P1(MyFileName::String)
  P, h, n, w1, w2, l, g, t = read_instance(MyFileName)
  w1 = 1
  w2 = 5

  # Create the model
  m = Model(CPLEX.Optimizer)

  ## Variables
  @variable(m, x[1:n+2,1:h+2], Bin)
  @variable(m, d[1:n+2,1:h+2] >= 0)

  ## Constraints
  @constraint(m, [i in 2:n+1, j in 2:h+1], d[i,j] <= x[i,j+1] + x[i+1,j] + x[i-1,j] + x[i,j-1] - 4 * (1 - x[i,j]))
  @constraint(m, sum(x[i,j] for i in 2:n+1, j in 2:h+1) >= 60)

  ## Objective
  @objective(m, Max, w1 * sum(t[i-1,j-1]*(1-x[i,j]) for i in 2:n+1, j in 2:h+1) + w2*g*l*sum(4*x[i,j] - d[i,j] for i in 2:n+1, j in 2:h+1))

  #resolution
  optimize!(m)

  # solution_summary(m, verbose=true)
  # z_vals = JuMP.getvalue.( m[:z] )
  # println(z_vals)

end

function P2(MyFileName::String)
  P, h, n, w1, w2, l, g, t = read_instance(MyFileName)
  w1 = 1
  w2 = 5

  # Create the model
  m = Model(CPLEX.Optimizer)

  ## Variables
  @variable(m, x[1:n+2,1:h+2] >= 0)
  @variable(m, y[1:n+2,1:h+2,1:n+2,1:h+2] >= 0)

  ## Constraints
  @constraint(m, [i in 1:n+2, j in 1:h+2], x[i,j] <= 1)
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i-1,j] <= x[i,j])
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i+1,j] <= x[i,j])
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i,j-1] <= x[i,j])
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i,j+1] <= x[i,j])

  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i-1,j] <= 1 - x[i-1,j])
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i+1,j] <= 1 - x[i+1,j])
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i,j-1] <= 1 - x[i,j-1])
  @constraint(m, [i in 2:n+1, j in 2:h+1], y[i,j,i,j+1] <= 1 - x[i,j+1])

  @constraint(m, sum(x[i,j] for i in 2:n+1, j in 2:h+1) >= 60)

  ## Objective
  @objective(m, Max, w1 * sum(t[i-1,j-1]*(1-x[i,j]) for i in 2:n+1, j in 2:h+1) + w2*g*l*sum(y[i,j,i-1,j] +  y[i,j,i+1,j] + y[i,j,i,j-1] + y[i,j,i,j+1] for i in 2:n+1, j in 2:h+1))

  #resolution
  optimize!(m)

  println(JuMP.value.(x))
  println(time() - start)

end

P2("output30.txt")
