using CSV
using ZipFile
using Dates
using DataFrames
using Plots
using DataSets
using Underscores

function load_truefx_csv(csv_blob)
    @info "Loading $(basename(csv_blob))"
    open(IO, csv_blob) do io
        zipped_content = only(ZipFile.Reader(io).files)
        buf = read(zipped_content)
        CSV.read(buf, DataFrame,
                 header=["pair", "timestamp", "bid", "ask"],
                 dateformat=dateformat"yyyymmdd H:M:S.s",
                 types=Dict(:timestamp=>DateTime))
    end
end

function candlestick_plot(timestamp, open, high, low, close)
    ohlc_min = min.(open, close)
    ohlc_max = max.(open, close)
    #movement = abs.(ohlc.open .- ohlc.close)
    sel = open .< close
    bar(timestamp[sel], ohlc_min[sel], fillrange=ohlc_max[sel], color=:green,
        linecolor=invisible(), label=nothing)
    bar!(timestamp[sel], low[sel], fillrange=high[sel], color=:green,
         linecolor=:green, bar_width=1, label=nothing)
    sel = open .> close
    bar!(timestamp[sel], ohlc_min[sel], fillrange=ohlc_max[sel], color=:red,
         linecolor=invisible(), label=nothing)
    bar!(timestamp[sel], low[sel], fillrange=high[sel], color=:red,
         linecolor=:red, bar_width=1, label=nothing)
end
function candlestick_plot(d::AbstractDataFrame)
    candlestick_plot(d.timestamp, d.open, d.high, d.low, d.close)
end

#-------------------------------------------------------------------------------
# Script
if isfile("ohlc_data.csv")
    # Plotting the OHLC data
    ohlc = CSV.read("ohlc_data.csv", DataFrame)
    min_time = minimum(ohlc.timestamp)
    first_quarter_ohlc = ohlc[ohlc.timestamp .< min_time + Month(3), :]

    for group in groupby(first_quarter_ohlc, :pair)
        pair = first(group.pair)
        candlestick_plot(group)
        plot!(size=(800, 300))
        title!(pair)
        base_currency, quote_currency = split(pair, '/')
        ylabel!(quote_currency)
        filename = "$base_currency$quote_currency.svg"
        @info "Saving $pair graph to file" filename
        savefig(filename)
    end
else
    DataSets.load_project!(path"Data.toml")

    # Plotting the raw data
    data = open(BlobTree, dataset("currency_data")) do tree
        load_truefx_csv(tree["EUUUDD-2020-01.zip"])
    end
    plot(data.timestamp, data.bid, label=nothing,
         title=data.pair[1], ylabel=split(data.pair[1], '/')[2])
    savefig("EUUUDD-2020-01.png")
end
