from django.contrib import admin
from outils.common_imports import *
from outils.for_view_imports import *
from django.views.generic import View
from django.http import HttpResponse
from django.http import JsonResponse

# Register your models here.
import os
from datetime import date
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment

from reception.models import CagetteReception
from outils.common import OdooAPI
from members.models import CagetteUser
from products.models import CagetteProduct



def index(request):
    """Accueil admin"""
    if 'reception' in settings.COUCHDB['dbs']:
        context = {
            'title': 'Admin Reception',
        }
        template = loader.get_template('reception/admin.html')

        return HttpResponse(template.render(context, request))
    else:
        return HttpResponse("Need to configure reception couchdb db in settings_secret.py")


def get_backups(request):
    orders = []
    po_ids = []

    for file in os.listdir('data/receptions_backup'):
        if '.json' in file:
            with open('data/receptions_backup/' + file, 'r') as json_file:
                bup = json.load(json_file)
                for oid, o in bup['orders'].items():
                    if 'br_valid' in file:
                        [bup['id'], timestamp] = file.split('_br_valid_')
                    else:
                        [bup['id'], timestamp] = file.split('_qty_valid_')
                    bup['date'] = datetime.datetime.fromtimestamp(int(timestamp.replace('.json', ''))/1000).strftime("%d/%m/%Y")
                    if len(o['po']) > 0:
                        bup['supplier'] = o['po'][0]['partner_id'][1]
                        bup['id'] = o['po'][0]['id_po']
                    else:
                        po_ids.append(int(bup['id']))
                orders.append(bup)
            if len(po_ids) > 0:
                api = OdooAPI()
                cond = [['id', 'in', po_ids]]
                fields = ['partner_id']
                res = api.search_read('purchase.order', cond, fields)
                for r in res:
                    for order in orders:
                        if 'id' in order:
                            if str(order['id']) == str(r['id']):
                                order['supplier'] = r['partner_id'][1]
                                continue




    return JsonResponse({'data': orders, 'po_ids': po_ids}, safe=False)
