
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 django.http import HttpResponse
import json
from django.http import JsonResponse
from serial import Serial
from articles.views import get_skill


# Create your views here.
def operator_page(request):
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getOperator')
   data_send = response.json()
   data_operator = data_send['response']
   if data_operator == 11:
         data_operator = [] 
   return render(request, 'operators/operator.html',context={'data_operator': data_operator})

# Create your views here.
def get_operator_data():  # sourcery skip: inline-immediately-returned-variable
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getOperator')
   data_send = response.json()
   data = data_send['response']
   if data == 11:
     data = []  
   return data

def operatorsHourly(request):
        if request.method == 'GET':
            response = requests.get('https://thingsaccess.com/rfid/index.php/api/getActiveOperatorsInaDay')
            data_send = response.json()
            print(data_send)
            dataOperator = data_send['response']
            return JsonResponse({'response': dataOperator})

def Add_operator(request):
   skills = get_skill()  
   if request.method == 'POST':
        data_json = json.loads(request.body)
        data = {
            'Name': data_json.get('Name'),
            'cnic': data_json.get('cnic'),
            'cell': data_json.get('cell'),
            'address': data_json.get('address'),
            'skill': data_json.get('skill'),
            'tag_id': data_json.get('tag_id')
        }
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/addOperator', json=data)
        data_send = response.json()
        data_article = data_send['response']
        return JsonResponse({'data_article': data_article})
      #   if response.status_code == 200:
      #       return redirect('operator_page')
      #       # messages.success(request, 'Data added successfully')
      #   else:
      #       # Insertion failed, show error message to user
      #        messages.error(request, 'Failed to add data')
            # return HttpResponse("Operator not added")

   return render(request, 'operators/addOperator.html',context={'skills':skills})

def Edit_Operator(request,id):
   skills = get_skill()  
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getOperator')
   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,
                'Name': request.POST.get('Name'),
                'cnic': request.POST.get('cnic'),
                'cell': request.POST.get('cell'),
                'address': request.POST.get('address'),
                'skill': request.POST.get('skill'),
                'tag_id': request.POST.get('tag_id'),
                'wage': request.POST.get('wage'), 
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/editOperator', json=data)
         if response.status_code == 200:
               return redirect('operator_page')
               # messages.success(request, 'Data added successfully')
         else: 
               
               # Insertion failed, show error message to user
               return HttpResponse("Operator not updated")
               # messages.error(request, 'Failed to edit data')
              

   return render(request,'operators/editOperator.html',context={'item': edit_item,'skills':skills})


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

def get_operator_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:
            print(data)
            try:
                decoded_data = data.decode()  # Assuming the received data is a valid string
                number_start_index = decoded_data.index('O') + 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
                print('Number:', number)
                break  # Stop reading after receiving a number
            except ValueError:
                pass
   except KeyboardInterrupt:
      pass

   finally:
      # Close the port
      ser.close()
   return number

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

   