###
# For Plotting.
###

function get_time_pred(Tm, Tgt, day_start, day_end, label, a; lc1, lc2, title="", lane_idx=1)
    tgt = vec( vcat( [Tgt[q,:,:,lane_idx] for q = day_start:day_end]... )' )
    tm  = vec( vcat( [Tm[q,:,:,lane_idx]  for q = day_start:day_end]... )' )
    len_days = day_end - day_start + 1
    day2min = 1440
    n_x  = 288
    cnt  = 2
    xaxis= ("Day", (0,+Inf), ([0:n_x:n_x*len_days;],[1:1:len_days+1;]))
    yaxis= ("Spped (mph)", (0,90))
    
    p = plot(legend=:bottomleft, xaxis=xaxis, yaxis=yaxis, tickfontsize=tfsize, legendfontsize=lfsize)
    plot!(p, tgt, label="GT", lc=lc1)
    plot!(p, tm, label=label, lc=lc2, title=title*" Lane $lane_idx")
    return p
end

function plot_missing_area(p, miss_min_interval;  color=:red, alpha=0.2, size=(600,400))
    plot!(p, size=plt_size, xlim=(0,1000))
    vspan!(p, miss_min_interval, color = :red, alpha = 0.1, labels=false)
end

function plot_baseline(reconv, T, day_start, day_end, method, title, plt_lanes, score, mr, miss_min_interval, fstr; a=1)
    plts = Dict{Int, Plots.Plot}( l => plot() for l in plt_lanes )
    for lane_idx in plt_lanes
        p = get_time_pred(reconv, T, day_start,day_end, method, a, lc1=lc_GT, lc2=lc_m3, title=title, lane_idx=lane_idx)
        p = plot_missing_area(p, miss_min_interval[lane_idx], size=plt_size)
        plts[lane_idx] = p
    end
    
    n_plt = length(plt_lanes)
    if n_plt == 4
        layout = (2,2) 
    else
        layout = (n_plt,1) 
    end
    p = plot( [ plts[l] for l=1:n_plt ]..., layout=layout, size=(1800,600), plot_title="\n Fit $score ml $mr")
    
    save_name = "results/mr$fstr/reconst_$method.pdf"
    savefig(p, save_name)
    println("$save_name has been saved.")
end

function plt_result(load_name, gt_file; day_start=1, day_end=28, plt_lanes=[1,2,3,4])
    load_dir = "results/$gt_file/$load_name.jld2"
    T_pred = load(load_dir)["result"]
    fit_score = load(load_dir)["score"]
    miss_min_interval = load(load_dir)["miss_interval"]
    
    gt_file = "data/traffic/preprocess/$gt_file.jld2"
    T = load(gt_file)["GT"]
    mr = load(gt_file)["mr"];
    fstr = Int( round(mr*100,digits=0) )

    plts = Dict{Int, Plots.Plot}( l => plot() for l in plt_lanes )
    for lane_idx in plt_lanes
        p = get_time_pred(T_pred, T, day_start, day_end, load_name, a, lc1=lc_GT, lc2=lc_m3, title="", lane_idx=lane_idx)
        p = plot_missing_area(p, miss_min_interval[lane_idx], color=miss_color, alpha=miss_alpha, size=plt_size)
        plts[lane_idx] = p
    end
    save_name = "results/mr$fstr/reconst_LRTC$load_name.pdf"
    p = plot( [ plts[l] for l=1:4 ]..., layout=(2,2), size=(1800,600), plot_title="\n Fit $fit_score mr $mr")
    savefig(p, save_name)
    println("$save_name has been saved.")
end