export runsimulation

"""
runprocess(;simulated=false, webservice=true, port=8000, σ = 0.001, duration = 14400)

Run the doubletank process with a GUI.
"""
function runsimulation(;simulated=true, webservice=true, port=8000, σ = 0.001, duration = 14400)
    R = DoubleTankSimulator(σ = σ)

    inspectdr(show=false)

    function run_process(P, gui, pidcontroller, duration = duration) #four hours
        y = 0.0
        u = 0.0
        n = 1
        start_time = time()
        for t in 0:P.h:duration
            y  = measure(P)[n]
            r = gui[:r]
            if gui[:tankno]=="Upper"
                n = 1
            else
                n = 2
            end
            onv = Int.([gui[s]=="On" for s in [:pOn, :iOn, :dOn]])
            rv = pidcontroller(r, y, onv)
            if gui[:mode]=="Automatic"
                gui[:u] = clamp(round(rv,digits=2), 0, 1) #u's constructor has only a dummy graphic so this is fine
                control(P, rv)
            elseif gui[:mode]=="Manual"
                control(P, gui[:u])
                #bumpless transfer:
                if gui[:iOn]=="On"
                    pidcontroller.I = gui[:u]-(pidcontroller.Tot-pidcontroller.I)
                end
            end
            push!(gui, y, 1)
            push!(gui, r, 2)
            push!(gui, pidcontroller.P, 3)
            push!(gui, pidcontroller.I, 4)
            push!(gui, pidcontroller.D, 5)
            push!(gui, pidcontroller.Tot, 6)
            push!(gui, t, 7)

            end_time = time()
            sleep_time = P.h + start_time - end_time
            if sleep_time ≥ 0.001
                sleep(sleep_time)
            end
            start_time = end_time
        end
    end

    plot_fps = 2
    gui_fps = 5
    g1, r1, tp = makegui(R, run_process, plot_fps, gui_fps)

    webio_serve(page("/", r1), port)
end