import pandas as pd
import json
import requests
from datetime import datetime

webservice = 'https://mappsacc.mazdaeur.com/dogma-restapi-dms/api'
module = '/vehicles/workshop/order-report'
authorization = 'https://mappsacc.mazdaeur.com/oauth/authorize'
token_url = 'https://mappsacc.mazdaeur.com/oauth/token'
user = 'mmd88888.cdk'
password = 'xNuh7fQzGfPfGJg'
token = 'MDDq3CUd9ix0iSqR'


def date_format(d):
    return d.isoformat() + "Z"


def convert_csv(csv_file, json_file):
    date_cols = ['invoiceDate', 'orderDate', 'orderCompletionDate', 'vehicleIntakeDate', 'nextMotDueDate']
    df = pd.read_csv(csv_file, encoding='ansi', decimal=',', sep=';', parse_dates=date_cols)
    # print(df[['currency','documentType','invoiceCategory','invoiceDate','invoiceNumber']].drop_duplicates().info())
    invoices = df[['currency', 'documentType', 'invoiceCategory', 'invoiceDate', 'invoiceNumber']].drop_duplicates().to_dict('records')
    invoice_items = df[['invoiceNumber', 'orderLineNumber', 'orderNumber', 'amount', 'discount', 'portion', 'unitPrice']].groupby('invoiceNumber')

    for invoice in invoices:
        invoice['invoiceDate'] = date_format(invoice['invoiceDate'])
        items = invoice_items.get_group(invoice['invoiceNumber'])
        items.pop('invoiceNumber')
        invoice['invoiceItems'] = items.to_dict('records')

    orders = df[['orderNumber', 'orderDate', 'orderCompletionDate', 'vehicleIntakeDate']].drop_duplicates().to_dict('records')
    orders_vehicle = df[['orderNumber', 'licensePlate', 'nextMotDueDate', 'odometer', 'odometerUnit', 'vin']].drop_duplicates().groupby('orderNumber')
    orders_items = df[[
        'orderNumber', 'lineNumber',
        'category', 'description', 'hours', 'operationCode', 'standardHours',
        'description.1', 'type',
        'description.2', 'isDamageCausal', 'manufacturer', 'partNumber', 'quantity', 'serialNumber', 'unit',
        'company', 'description.3', 'invoiceCode', 'invoiceDate', 'invoiceNumber'
    ]].drop_duplicates().groupby('orderNumber')

    for order in orders:
        order['vehicle'] = orders_vehicle.get_group(order['orderNumber']).to_dict('records')[0]
        order['vehicle']['nextMotDueDate'] = date_format(order['vehicle']['nextMotDueDate'])

        order['orderDate'] = date_format(order['orderDate'])
        order['orderCompletionDate'] = date_format(order['orderCompletionDate'])
        order['vehicleIntakeDate'] = date_format(order['vehicleIntakeDate'])

        items = orders_items.get_group(order['orderNumber']).to_dict('records')
        order['items'] = []
        for item in items:
            order['items'].append({
                'lineNumber': item['lineNumber'],
                'operation': {
                    'category': item['category'],
                    'description': item['description'],
                    'hours': item['hours'],
                    'operationCode': item['operationCode'],
                    'standardHours': item['standardHours']
                },
                'other': {
                    'description': item['description.1'],
                    'type': item['type']
                },
                'part': {
                    'description': item['description.2'],
                    'isDamageCausal': item['isDamageCausal'],
                    'manufacturer': item['manufacturer'],
                    'partNumber': item['partNumber'],
                    'quantity': item['quantity'],
                    'serialNumber': item['serialNumber'],
                    'unit': item['unit']
                },
                'purchaseInvoice': {
                    'company': item['company'],
                    'description': item['description.3'],
                    'invoiceCode': item['invoiceCode'],
                    'invoiceDate': date_format(item['invoiceDate']),
                    'invoiceNumber': item['invoiceNumber']
                }
            })

    date_min = str(df['invoiceDate'].min()) + 'T00:00:00.000Z'
    date_max = str(df['invoiceDate'].max()) + 'T00:00:00.000Z'

    res = {
        'creationDate': str(datetime.now()),
        'invoices': invoices,
        'orders': orders,
        'timeRangeBegin': date_min,
        'timeRangeEnd': date_max
    }

    json.dump(res, open(json_file, 'w'), indent=2)
    return res


def upload(data):
    headers = {
        'accept': 'application/vnd.mazdaeur.dms.v3+json',
        'x-mme-organisation': '10030/MMD',
        'Content-Type': 'application/json',
        # 'Authorization': 'Bearer ' + token
    }
    s = requests.Session()
    s.auth = (user, password)
    s.headers.update(headers)
    # r = s.post(webservice + module, data=data)
    r = s.get(authorization + '?response_type=code&client_id=globalcube&state=xyz&scope=write')
    print(r.text)
    r = s.post(token_url, data={'grant_type': 'authorization_code', 'code': ''})
    print(r.text)


def main():
    # data = convert_csv('nasa/Workshop_Order_Report.csv', 'nasa/mazda_export.json')
    data = json.load(open('nasa/mazda_export.json', 'r'))
    upload(data)


if __name__ == '__main__':
    main()
