from django.shortcuts import render
from django.contrib import messages
from django.shortcuts import redirect
import requests

import serial
import time
from serial import Serial
from django.http import JsonResponse
import subprocess


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


def Add_skill(request):
        if request.method == 'POST':
                data = {
                    'title': request.POST.get('title')
                }
                response = requests.post('https://thingsaccess.com/rfid/index.php/Api/addSkills', json=data)
                if response.status_code == 200:
                    return redirect('skill_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, 'skill/addskill.html')        


def Edit_skill(request,id):
       # tag_id = get_bundle_tag_id()
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getSkills')
   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,
               'title': request.POST.get('title'),
             
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/editSkills', json=data)
         if response.status_code == 200:
               return redirect('skill_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,'skill/editskill.html',context={'item': edit_item})

def delete_skill(request,id):
   data_delete = {
        'id': id
   }
 
   response = requests.post('https://thingsaccess.com/rfid/index.php/Api/deleteSkills', json=data_delete)
   if response.status_code == 200:
        return redirect('skill_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")