
from django.shortcuts import render
from django.contrib import messages
from django.shortcuts import redirect
import requests
from django.http import HttpResponse
from django.http import JsonResponse
# Create your views here.

def get_article_group():
    response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getArticleMainBundle')
    data_send = response.json()
    return data_send['response']
   

def articlegroup_page(request):
   data_articlegroup=get_article_group()
   return render(request, 'ArticleGroup/articleGroup.html',context={'data_articlegroup': data_articlegroup})


def Add_ArticleGroup(request):
   if request.method == 'POST':
        data = {
            'title': request.POST.get('title'),
            'bundle_size': request.POST.get('bundle_size'),

        }
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/addArticleMainBundle', json=data)
        if response.status_code == 200:
            return redirect('articlegroup_page')
            # messages.success(request, 'Data added successfully')
        else:
            # Insertion failed, show error message to user
            # messages.error(request, 'Failed to add data')
            return HttpResponse("article group not added")

   return render(request, 'ArticleGroup/addArticleGroup.html')

def Edit_Article_group(request,id):
   data = get_article_group()
   edit_item = None
   for item in data:
        if item['id'] == id:
            edit_item = item
            break
   if edit_item:
      if request.method == 'POST':
         data = {
                'id':id,
                'title': request.POST.get('title'),
                'bundle_size': request.POST.get('bundle_size'),
                
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/editArticleMainBundle', json=data)
         if response.status_code == 200:
               return redirect('articlegroup_page')
               # messages.success(request, 'Data added successfully')
         else:
               # Insertion failed, show error message to user
               messages.error(request, 'Failed to edit data')
              

   return render(request,'ArticleGroup/editArticleGroup.html',context={'item': edit_item})


def delete_Article_group(request,id):
   data_delete = {
        'id': id
   }
   print(data_delete)
   response = requests.post('https://thingsaccess.com/rfid/index.php/Api/deleteArticleMainBundle', json=data_delete)
   if response.status_code == 200:
      return redirect('articlegroup_page')
   messages.error(request, 'Failed to delete data')
   return HttpResponse("Operator not deleted")
   


   