module LogiFaces

# Usage:
# julia> foreach(p -> LogiFaces.generate(p), LogiFaces.pieces)

# Or:
# julia> LogiFaces.generate_all()

unit = 8 # mm
edge = 5 # units
gapy = 10 # mm
gapz = 6 # mm
pieces = [(1,1,1), (1,1,2), (1,1,3), (1,2,2), (1,2,3), (1,3,2), (1,3,3), (2,2,3), (2,3,3), (3,3,3)]
# 16         1        2        1        1        2        2        1        2        3        1

function write_piece(stream, piece, position, index)
    angles = [0, 2π/3, 4π/3]
    tri = [[cos(ϕ) sin(ϕ) 0] * edge * unit / sqrt(3) + position for ϕ in angles]
    p = vcat(tri[1], tri[2], tri[3], [tri[i] + [0 0 piece[i]*unit] for i in 1:3]...)
    for i in 1:6
        println(stream, "v $(p[i,1]) $(p[i,2]) $(p[i,3])")
    end
    faces = [[1, 2, 3], [1, 2, 5, 4], [2, 3, 6, 5], [3, 1, 4, 6], [4, 5, 6]]
    for face in faces
        println(stream, "f " * join([index * 6 + i for i in face], " "))
    end
end

function generate(piece)
    filename = "/tmp/" * join(piece) * ".obj"
    open(filename, "w") do f
        write_piece(f, piece, [0 0 0], 0)
    end
end

function generate_all()
    board = [(1,1,1) (1,1,2) (1,1,2) (1,1,3) (1,2,2) (1,2,3)
             (1,2,3) (1,3,2) (1,3,2) (1,3,3) (2,2,3) nothing
             (2,3,3) (2,3,3) (2,3,3) (3,3,3) (2,2,3) nothing]
    open("/tmp/logifaces.obj", "w") do f
        index = 0
        for i in 1:3, j in 1:6
            board[i,j] === nothing && continue
            sum_thickness = sum([reduce(max,board[i,k]) for k in 1:j-1])
            write_piece(f, board[i,j], [0 i*(edge*unit+gapy) sum_thickness*unit+j*gapz], index)
            index += 1
        end
    end
end

end # module