from django.shortcuts import render
from django.contrib import messages
from django.shortcuts import redirect
import requests
from django.http import HttpResponse
import serial
import time
from serial import Serial
from django.http import JsonResponse
import subprocess


# Create your views here.
def bundle_page(request):
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getBundle')
   data_send = response.json()
   data_bundle = data_send['response']
   if data_bundle == 11:
         data_bundle = []  
   return render(request, 'bundles/bundle.html',context={'data_bundle': data_bundle})



def Add_bundle(request):
   if request.method == 'POST':
        data = {
            'article_ID': request.POST.get('article_ID'),
            'tag_ID': request.POST.get('tag_ID'),
            'step_ID': request.POST.get('step_ID'),
            'bundleSize': request.POST.get('bundleSize'),
            'state': request.POST.get('state'),
            'status': request.POST.get('status'),
        }
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/addBundle', json=data)
        if response.status_code == 200:
            return redirect('bundle_page')
            # messages.success(request, 'Data added successfully')
        else:
            # Insertion failed, show error message to user
            messages.error(request, 'Failed to add data')

   return render(request, 'bundles/addBundle.html')

def get_bundle_tag_id():
    number = None
    ser = serial.Serial(port='COM9', baudrate=115200, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
    try:
        # Read data from the port
        while True:
            data = ser.readline().strip()  # Remove whitespace characters from the received data

            if data:
                try:
                    decoded_data = data.decode()  # Assuming the received data is a valid string
                    number_start_index = decoded_data.index('B') + 1  # Find the index of 'B' and add 1 to skip it
                    number = int(decoded_data[number_start_index:])  # Extract the number portion and convert it to an integer
                    break  # Stop reading after receiving a number
                except ValueError:
                    pass
    except KeyboardInterrupt:
        pass
    finally:
        # Close the port
        ser.close()
    return number

def get_tag_id(request):
    if request.method == 'GET':
        number = get_bundle_tag_id()  # Call your function to get the tag ID
        response = {'number': number}
        print(response)
        return JsonResponse(response)



def Edit_Bundles(request,id):
   # tag_id = get_bundle_tag_id()
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getBundle')
   data_send = response.json()
   data = data_send['response']
   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,
               'article_ID': request.POST.get('article_ID'),
               'tag_ID': request.POST.get('tag_ID'),
                
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/editBundle', json=data)
         if response.status_code == 200:
               return redirect('bundle_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,'bundles/editBundle.html',context={'item': edit_item})


def delete_Bundle(request,id):
   data_delete = {
        'id': id
   }
   print(data_delete)
   response = requests.post('https://thingsaccess.com/rfid/index.php/Api/deleteBundle', json=data_delete)
   if response.status_code == 200:
        return redirect('bundle_page')
        # messages.success(request, 'Data added successfully')
   else:
        # Insertion failed, show error message to user
       messages.error(request, 'Failed to delete data')
       return HttpResponse("Bundle not deleted")

   