import json
from dataclasses import dataclass
from pathlib import Path

from requests_oauthlib import OAuth2Session

from mazda_export import convert_csv


@dataclass
class MazdaConfig:
    domain: str
    webservice: str
    module: str
    auth_url: str
    token_url: str
    client_id: str
    client_secret: str
    username: str
    password: str
    dealer_number: str


cfg_prod = MazdaConfig(
    domain="https://mapps.mazdaeur.com",
    webservice="/dogma-restapi-dms/api",
    module="/vehicles/workshop/order-report",
    auth_url="/oauth/authorize",
    token_url="/oauth/token",
    client_id="2F6FACF0-F216-FB26-868A-BAAF82890E62",
    client_secret="8scMw?34ecQT)M=7!C=LQ",
    username="mmd15972.globalcube2",
    password="fBYxJ!nfj)4?E3N",
    dealer_number="15972/MMD",
)

cfg_debug = MazdaConfig(
    domain="https://mappsacc.mazdaeur.com",
    webservice="/dogma-restapi-dms/api",
    module="/vehicles/workshop/order-report",
    auth_url="/oauth/authorize",
    token_url="/oauth/token",
    client_id="E7FC943B-B73F-F48E-B71A-419EA4CD4AC7",
    client_secret="^bH=rk@c58zrr^Apc#9fzy$c",
    username="mmd88888.cdk",
    password="MazdaCX30",
    dealer_number="15972/MMD",
)


redirect_uri = "https://localhost:8085/"
base_dir = "C:/projekte/mazda/"


def upload(cfg: MazdaConfig, oauth: OAuth2Session, data):
    headers = {
        "accept": "application/vnd.mazdaeur.dms.v5+json",
        "x-mme-organisation": cfg.dealer_number,
        "X-mazda-org": cfg.dealer_number,
        "Content-Type": "application/json",
        # 'Authorization': 'Bearer ' + token
    }

    invoices = data["invoices"]
    orders = data["orders"]
    data["orders"] = []
    for i in invoices:
        data["invoices"] = [i]
        order_no = [item["orderNumber"] for item in i["invoiceItems"]]
        data["orders"] = [o for o in orders if o["orderNumber"] in order_no]
        r = oauth.post(cfg.domain + cfg.webservice + cfg.module, json.dumps(data), headers=headers)
        print(f"{i['invoiceNumber']} => {r.status_code}")
        if r.status_code not in [200, 202]:
            with open(base_dir + f"logs/invoice_{i['invoiceNumber']}.log", "wb") as fwh:
                fwh.write(r.content)


def upload_files(cfg: MazdaConfig, oauth: OAuth2Session):
    headers = {
        "accept": "application/vnd.mazdaeur.dms.v5+json",
        "x-mme-organisation": cfg.dealer_number,
        "X-mazda-org": cfg.dealer_number,
        "Content-Type": "application/json",
    }
    result = []
    print("Upload Files")

    for order_file in Path(base_dir + "export/Mazda").glob("*.json"):
        data = json.load(order_file.open("r"))

        r = oauth.post(cfg.domain + cfg.webservice + cfg.module, json.dumps(data), headers=headers)
        print(f"{order_file.name} => {r.status_code}")
        result.append(f"{order_file.name} => {r.status_code}")
        if r.status_code in [200, 202]:
            # OK
            # order_file.unlink()
            order_file.rename(base_dir + "export/Mazda/success/" + order_file.name)
        else:
            with open(base_dir + f"logs/{order_file.name}.log", "wb") as fwh:
                fwh.write(r.content)
            order_file.rename(base_dir + "export/Mazda/error/" + order_file.name)

    return result


def main():
    data = convert_csv(base_dir + "data/Workshop_Order_Report.csv", base_dir + "temp/mazda_export.json", 2021, 6)
    # data = json.load(open(base_dir + 'mazda_export.json', 'r'))
    upload(cfg_debug, None, data)


if __name__ == "__main__":
    main()
