using CSV
using DataFrames
using HTTP
using StringViews
using JSON
using Dates

using Plots
using StatsPlots
using Colors
theme(:ggplot2)

kraken = """
cryptocurrency	confirmationMinutes
0x (ZRX)	5
1inch (1INCH)	5
Aave (AAVE)	5
Aavegotchi (GHST)	5
Algorand (ALGO)	0.75
Ankr (ANKR)	5
Aragon (ANT)	5
Augur (REP)	5
Augur v2 (REPV2)	5
Axie Infinity (AXS)	5
Badger DAO (BADGER)	5
Balancer (BAL)	5
Bancor (BNT)	5
Band Protocol (BAND)	5
Basic Attention Token (BAT)	5
Bifrost (BNC)	4
Bitcoin (BTC)	40
Cardano (ADA)	10
Cartesi (CTSI)	5
Chainlink (LINK)	5
Chiliz (CHZ)	5
Compound (COMP)	5
Cosmos (ATOM)	0
Covalent (CQT)	5
Curve (CRV)	5
Dash (DASH)	5
Dai (DAI) ERC-20	5
Decentraland (MANA)	5
Dogecoin (DOGE)	40
dYdX (DYDX)	5
Energy Web Token (EWT)	1.75
Enjin Coin (ENJ)	5
Enzyme Finance (MLN)	5
EOS (EOS)	0
Ethereum (ETH)	5
Flow (FLOW)	1
Gnosis (GNO)	5
ICON (ICX)	0
Injective Protocol (INJ)	5
Karura (KAR)	4
Kava (KAVA)	0
Keep Network (KEEP)	5
Kusama (KSM)	2
Kyber Network (KNC)	5
Lisk (LSK)	51
Litecoin (LTC)	30
Livepeer (LPT)	5
Loopring (LRC)	5
Maker (MKR)	5
Mina (MINA)	60
Mirror Protocol (MIR)	5
Monero (XMR)	30
Moonriver (MOVR)	4
Nano (XNO)	0
Ocean (OCEAN)	5
OmiseGO (OMG)	5
Orchid (OXT)	5
Origin Protocol (OGN)	5
Oxygen (OXY)	0
PAX Gold (PAXG)	5
Perpetual Protocol (PERP)	5
Phala (PHA)	5
Polkadot (DOT)	2
Polygon (MATIC)	5
Qtum (QTUM)	60
Rarible (RARI)	5
Raydium (RAY)	0
REN Protocol (REN)	5
Ripple (XRP)	0
Serum (SRM)	0
Shiden (SDN)	4
Siacoin (SC)	60
Solana (SOL)	0
Stellar Lumens (XLM)	0
Storj (STORJ)	5
Sushi (SUSHI)	5
Synthetix (SNX)	5
tBTC (TBTC)	5
Tether USD (USDT) ERC-20	5
Tezos (XTZ)	15
The Graph (GRT)	5
The Sandbox (SAND)	5
Tron (TRX)	1
Uniswap (UNI)	5
USD Coin (USDC)	5
Waves (WAVES)	10
Wrapped Bitcoin (WBTC)	5
Yearn Finance (YFI)	5
Zcash (ZEC)	60
"""

df = CSV.File(IOBuffer(kraken)) |> DataFrame

df.symbol = [split(split(sym, "(")[end], ")")[1] |> lowercase for sym in df.cryptocurrency]

coins = HTTP.get("https://api.coingecko.com/api/v3/coins/list").body |>
        StringView |> JSON.parse .|> DataFrame |> x -> vcat(x...)

coins = coins[coins.id.!="xeno-token", :]

coins = unique(coins[end:-1:1, :], :symbol);

df = innerjoin(df, coins, on = :symbol)

mktcap_url = "https://api.coingecko.com/api/v3/simple/price?vs_currencies=usd&include_market_cap=true&ids=" * join(df.id, ",")

caps = HTTP.get(mktcap_url).body |>
       StringView |> JSON.parse

df.mktcap = [caps[id]["usd_market_cap"] ./ 1e9 for id in df.id]
df = df[df.mktcap.!=0, :]


function imp_func(name)
    important = ["Bitcoin" "Ethereum" "Nano" "Dogecoin" "XRP" "Solana"]
    if name in important
        println(name)
        name |> typeof |> println
        return name
    else
        return ""
    end
end

df.important = imp_func.(df.name)
sort!(df, :confirmationMinutes)

let
    @df df[df.important.!="", :] scatter(:confirmationMinutes, :mktcap, group = :cryptocurrency, markersize = 6, alpha = 0.9)
    @df df[df.important.=="", :] scatter!(:confirmationMinutes, :mktcap, alpha = 0.5, label = "Other")

    title!("Market Cap vs. Confirmation Time")
    xlabel!("Confirmation Time (Minutes)")
    ylabel!("Market Cap (Billions USD)")
    # annotate!(12, 435, "Ethereum")
    # annotate!(45, 1010, "Bitcoin")
    annotate!(2, 1090, text("Prices as of: $(today())", :left, 8))
    plot!(legend = :topleft)

    savefig("caps.svg")
end

fast = df[df.confirmationMinutes.==0, :]


cats = [
    "cosmos" "Parachain"
    "icon" "Parachain"
    "kava" "DeFi"
    "nano" "Currency"
    "oxygen" "DeFi"
    "raydium" "DeFi"
    "serum" "DeFi"
    "solana" "Smart Contract"
    "stellar" "Parachain"
    "ripple" "Currency"
] |> x -> DataFrame(x, [:id, :category])

fast = innerjoin(cats, fast, on = :id)

let
    @df fast bar(
        :id,
        :mktcap,
        group = :category,
        xrotation = 15,
        legend = :topleft,
        # yaxis = :log10
        # fillcolor = [jlc.blue jlc.green jlc.purple jlc.red],
    )

    title!("Market Caps of Fast Coins")
    ylabel!("Market Cap (Billions USD)")
    savefig("fast.svg")
end