#!/usr/bin/env python3

from ten import *
from tenlib import *
from typing import Tuple
from os.path import exists
import sys, json, os
from rich.console import Console
from rich.table import Table

def journey(s):
    out.info("Getting journey")
    r = s.get("/customer-space/invoices/journeys")
    entrees = [
        i.find("div", {"class": "journey-consumption__station-info"}).get_text().strip()
        for i in r.soup.find_all("div", {"class": "journey-consumption__entry-station"})
    ]
    exites = [
        i.find("div", {"class": "journey-consumption__station-info"}).get_text().strip()
        for i in r.soup.find_all("div", {"class": "journey-consumption__exit-station"})
    ]
    prices = [
        i.find("div", {"class": "journey-consumption__price-info"}).get_text().strip()
        for i in r.soup.find_all("div", {"class": "journey-consumption__price"})
    ]
    times = [
        i.find("div", {"class": "journey-consumption__time-info"}).get_text().strip()
        for i in r.soup.find_all("div", {"class": "journey-consumption__badge"})
    ]
    a = ["Date;Depart;Arrivée;Prix"]
    for i in range(0, len(entrees)):
        a.append("{};{};{};{}".format(times[i], entrees[i], exites[i], prices[i]))
    utils.table.display("\n".join(a), "\n", ";")


def download_pdf(s, link, filename):
    with open(f"{filename}.pdf", "wb") as fd:
        with s.get(link, stream=True) as r:
            for chunk in r.iter_content(chunk_size=128):
                fd.write(chunk)


def factures(s, list, table):
    out.info("Get history")
    r = s.get("/customer-space/invoices/history/0/24")
    for i in r.soup.find_all("li", {"class": "invoice-info__list-item"}):
        price = i.find("div", {"class": "invoice-info__price-info"}).get_text().strip()
        link = i.find("a", {"class": "btn"}).get("href")
        month = link.split("/")[-1]
        status = ""
        if list:
            table.add_row(month, price, status)
            continue
        if exists(f"{month}.pdf"):
            status = "Already done"
            table.add_row(month, price, status)
            return
        else:
            download_pdf(s, link, month)
            status = "Downloaded"
            table.add_row(month, price, status)



@Flow
def main(config: str = ".config/aprr.cfg", current: bool = False, list: bool = False, proxy: bool = False):
    fc = open("{}/{}".format(os.getenv("HOME"), config))
    creds = json.load(fc)
    fc.close()
    out.info("Running...")
    s = ScopedSession("https://www.mango-mobilitesbyaprr.com/")
    if proxy:
        s.burp()
    r = s.get("/customer/login")
    f = r.form(id="kc-form-login")
    f["username"] = creds["username"]
    f["password"] = creds["passwd"]
    r = f.submit()
    if r.contains("Identifiez-vous"):
        failure("Authentication failed")
    else:
        out.success("Authenticated")
    if current:
        journey(s)

    table = Table(title="Factures")
    table.add_column("Date")
    table.add_column("Euros")
    table.add_column("Comments")
    factures(s, list, table)
    console = Console()
    console.print(table)

main()
