from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Csv
from .forms import *
from django.contrib import messages
import datetime
import csv

def note_upload(request):

    form = CsvModelForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        form = CsvModelForm()
        obj = Csv.objects.get(activated=False)
        with open(obj.file_name.path, 'rb') as f:
            reader = csv.reader(f)
            for i, row in enumerate(reader):
                if i == 0:
                    pass
                else:
                    row = "".join(row)
                    # on remplace les espaces avec par des " _ "
                    row = row.replace(" ", "_")
                    # on repmlace " ; " par des espaces
                    row = row.replace(";", " ")
                    row = row.split()

                    id = row[0]
                    slug = row[1]
                    name = row[1].replace("_", " ")
                    description = row[2].replace("_", " ")
                    price = row[3]
                    available = row[4]
                    stock = row[5]
                    category = Category.objects.get(id=row[6])

                    # ON ENREGISTRE LES DONNEES DANS LA TABLE

            obj.activated = True
            obj.save()

        messages.success(request, 'Votre fichier a été chargé avec succès')
    return render(request,'upload/product_upload.html',{'form':form})
