from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import json
from product_directory.models import Product
from .models import Warehouse, StockOperation
from django.http import HttpResponse

def scan_barcode_camera(request):
    return render(request, 'scan_barcode.html')

def get_product_by_barcode(request, barcode):
    """
    Возвращает информацию о продукте по штрих-коду.
    """
    try:
        product = Product.objects.get(barcode=barcode)
        response_data = {
            "name": product.name,
            "barcode": product.barcode,
            "shelf_life_days": product.shelf_life_days,
            "dimensions": product.dimensions,
            "unit_of_measure": product.unit_of_measure,
            "manufacturer": product.manufacturer,
            "category": product.get_category_display(),
            "storage_temperature": product.storage_temperature,
            "promotion": product.get_promotion_display() if product.promotion else "Нет акции"
        }
        print(response_data)
        return JsonResponse(response_data)
    except Product.DoesNotExist:
        return JsonResponse({"error": "Продукт с указанным штрих-кодом не найден"}, status=404)

@csrf_exempt
def process_barcode(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        barcode = data.get('barcode')

        print(barcode)

        # # Логика для обработки штрих-кода
        # country_code = int(barcode[:3])
        # manufacturer_code = barcode[3:7]
        # product_code = barcode[7:12]
        # control_digit = barcode[-1]

        return get_product_by_barcode(barcode)
    return JsonResponse({"error": "Метод не поддерживается"}, status=405)


def dashboard(request):
    incoming_count = StockOperation.objects.filter(operation_type='Incoming').count()
    outgoing_count = StockOperation.objects.filter(operation_type='Outgoing').count()
    transfer_count = StockOperation.objects.filter(operation_type='Transfer').count()
    writeoff_count = StockOperation.objects.filter(operation_type='WriteOff').count()

    return render(request, 'warehouse/dashboard.html', {
        'incoming_count': incoming_count,
        'outgoing_count': outgoing_count,
        'transfer_count': transfer_count,
        'writeoff_count': writeoff_count
    })

def warehouses_list(request):
    warehouses = Warehouse.objects.all()
    return render(request, 'warehouse/warehouses.html', {'warehouses': warehouses})

def operations_list(request):
    operations = StockOperation.objects.all()
    return render(request, 'warehouse/operations_list.html', {'operations': operations})

def add_warehouse(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        location = request.POST.get('location')
        if name and location:
            Warehouse.objects.create(name=name, location=location)
            return redirect('warehouses')
        return HttpResponse("Ошибка: заполните все поля", status=400)
    return render(request, 'warehouse/add_warehouse.html')