from django.shortcuts import render
import requests
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, get_user_model,logout
import json
import hashlib
from django.http import JsonResponse
from django.http import HttpResponse
from articles.views import get_article_data
from machine.views import get_machine_data
from articles.views import get_skill
from machine.views import get_machine_state
from django.core.cache import cache



User = get_user_model()

complete_bundle = []
totalBundle = []
progress_bundle = []
faulty_bundle = []

operator_info_state = []
machine_info_state = []

def login_page(request):
    global data_dashboard
    global operator_info_state
    global machine_info_state
   
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        data = {'email': email, 'password': password}
        headers = {'Content-Type': 'application/json'}
        # Set CORS headers
        # response = HttpResponse()
        # response["Access-Control-Allow-Origin"] = "*"  # Replace "*" with the appropriate origin or origins
        # response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
        # response["Access-Control-Allow-Headers"] = "Content-Type"

        # # Handle preflight requests
        # if request.method == "OPTIONS":
        #     return response

        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/login/', headers=headers, json=data)
        
        if response.status_code == 200:
            data = response.json()
            data_dashboard = data['response']
            
        
            
         
            bundle_info_state = data_dashboard['bundlesInfo']
            totalBundle = data_dashboard['bundlesInfo']['total']
            progress_bundle = data_dashboard['bundlesInfo']['inProgress']
            complete_bundle = data_dashboard['bundlesInfo']['completed']
            faulty_bundle = data_dashboard['bundlesInfo']['qualityError']
        
            # for i in range(len(bundle_info_state)):
            #       print(bundle_info_state[i]['inProgress'])
            # for i in range(len(bundle_info_state)):
            #     total_bundle = bundle_info_state[i]['state']
            #     if total_bundle == '3':
            #             complete_bundle.append(total_bundle)
            #     elif total_bundle == '2':
            #             progress_bundle.append(total_bundle)
            #     elif total_bundle == '4':    
            #             faulty_bundle.append(total_bundle)
            #     totalBundle.append(total_bundle)     
                       
                
            request.session['complete_bundle'] = complete_bundle
            request.session['totalBundle'] = totalBundle   
            request.session['progress_bundle'] = progress_bundle 
            request.session['faulty_bundle'] = faulty_bundle 
         
           
            operator_info_state = data_dashboard['operatorsInfo']

           
            # total_machine = []
            # idle_machine = []
            # active_machine = []
            # fault_machine = []
            # powerdown_machine = []
            # machine_info_state = []

            machine_info_state = data_dashboard['machinesInfo']
            # for i in range(len(machine_info_state)):
            #     totalMachine = machine_info_state[i]['state']
            #     if totalMachine == '1':
            #             idle_machine.append(totalMachine)
            #     elif totalMachine == '2':
            #             active_machine.append(totalMachine)
            #     elif totalMachine == '3':    
            #             fault_machine.append(totalMachine)
            #     elif totalMachine == '4':    
            #             powerdown_machine.append(totalMachine)
            #     total_machine.append(totalMachine)  
            
            # request.session['machine_info_state'] = machine_info_state
            # request.session['total_machine'] = total_machine
            # request.session['idle_machine'] = idle_machine   
            # request.session['active_machine'] = active_machine 
            # request.session['fault_machine'] = fault_machine 
            # request.session['powerdown_machine'] = powerdown_machine

            try:
                total_production = data_dashboard['articlesInfo'][0]['total_production']
                today_production = data_dashboard['articlesInfo'][0]['today_production']
                yesterday_production = data_dashboard['articlesInfo'][0]['yesterday_production']
                day_before_yesterday_production = data_dashboard['articlesInfo'][0]['day_before_yesterday_production']
                request.session['total_production'] = total_production
                request.session['today_production'] = today_production
                request.session['yesterday_production'] = yesterday_production
                request.session['day_before_yesterday_production'] = day_before_yesterday_production
            except (KeyError, IndexError):
                   request.session['total_production'] = 0
                   request.session['today_production'] = 0
                   request.session['yesterday_production'] = 0
                   request.session['day_before_yesterday_production'] = 0
           
            # Assuming the hashed password is in MD5 format
            # user_id = data_dashboard['userInfo']['id']
            hashed_password = data_dashboard['userInfo']['password_hash']
            md5_hasher = hashlib.md5()
            md5_hasher.update(hashed_password.encode('utf-8'))
            plain_password = md5_hasher.hexdigest()
            # print(plain_password,'pass')
            # plain_password = '12345678'
            try:
                # Try to retrieve the user by email
                user = User.objects.get(username=email)
                user.set_password(plain_password)  # Update the password if necessary
                user.save()
            except User.DoesNotExist:
                # Create a new user if the user doesn't exist
                user = User.objects.create_user(username=email, email=email, password=plain_password)
            
            # Authenticate and login the user
            login(request, user)
           # Store relevant data in the session
            try:
                request.session['articleinfo'] = data_dashboard['articleCount']
                request.session['operators_info'] = data_dashboard['operatorsCount']
                request.session['bundlesInfo'] = data_dashboard['bundleCount']
                request.session['machinesInfo'] = data_dashboard['machineCount']
                request.session['todayBundleCount'] = data_dashboard['todayBundleCount']
                request.session['monthlyBundleCount'] = data_dashboard['monthlyBundleCount']
            except (KeyError, IndexError):
                request.session['articleinfo'] = 0
                request.session['operators_info'] = 0
                request.session['bundlesInfo'] = 0
                request.session['machinesInfo'] = 0 
                request.session['todayBundleCount'] = 0 
                request.session['monthlyBundleCount'] = 0 
            
            return redirect('home') 

        elif response.status_code == 401:
            data = response.json()
            error_code = data['response']
            if error_code == -120:
                messages.error(request, 'Invalid email. Please try again.')
            elif error_code == -121:
                messages.error(request, 'Invalid password. Please try again.')
        else:    
            messages.error(request, 'Invalid email or password. Please try again.')

    return render(request, 'login/login.html')

def login_required(view_func):
    def _wrapped_view(request, *args, **kwargs):
        # Check if the user is authenticated
        if request.user.is_authenticated:
            return view_func(request, *args, **kwargs)
        else:
            # If the user is not authenticated, redirect to the login page
            return redirect('login_page')  # Replace 'login_page' with the actual URL name of your login page

    return _wrapped_view

@login_required
def home(request):
    # Retrieve session data
    global operator_info_state
    global machine_info_state
    print(len(operator_info_state),'home')

    articleinfo = request.session.get('articleinfo')
    operators_info = request.session.get('operators_info')
    bundlesInfo = request.session.get('bundlesInfo')
    machinesInfo = request.session.get('machinesInfo')
    today_bundle_count = request.session.get('todayBundleCount')
    monthly_bundle_count = request.session.get('monthlyBundleCount')
    return render(request, 'home/index.html', {'articleinfo': articleinfo, 'operators_info': operators_info, 'bundlesInfo': bundlesInfo, 'machinesInfo': machinesInfo,'monthly_bundle_count':monthly_bundle_count,'today_bundle_count':today_bundle_count})
    
def signup_page(request):
    if request.method == 'POST':
         email = request.POST.get('email')
         phone = str(request.POST.get('phone'))
         country_code = "0092"
         if phone.startswith('0'):
             phone = phone[1:]  # Remove the leading '0'
        
         full_phone_number = country_code +" "+ phone
         data = {
               'email': request.POST.get('email'),
               'first_name': request.POST.get('first_name'),
               'last_name': request.POST.get('last_name'),
               'password': request.POST.get('password'),
               'phone': full_phone_number,
               'role': request.POST.get('role')
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/signup', json=data)
         if response.status_code == 200:
               request.session['email'] = email 
               messages.success(request, 'Signup successfully')
               return redirect('email_verify')
               
         else:
            #  messages.error(request, 'Failed to Sign up please try again')  # Display error message
             return redirect('signup_page')
               
    return render(request, 'login/signup.html')


def email_verify(request):
    email = request.session.get('email')
    if request.method == 'POST':
        code1 = request.POST.get('code1')
        code2 = request.POST.get('code2')
        code3 = request.POST.get('code3')
        code4 = request.POST.get('code4')
        combine = code1+code2+code3+code4
        data = {
          'email': email,
          'activation_code':int(combine)
        }
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/verifyEmail', json=data)
        if response.status_code == 200:
               return redirect('login_page')
        else:
               return redirect('email_verify')
    # print(email,'email')
    return render(request, 'login/verifyemail.html', {'email':email})



def resend(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)    
        data = {
            'email': data_json.get('email'),
        }
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/verifyEmailOnly', json=data)
        data_send = response.json()
        resend_code = data_send['response']
        return JsonResponse({'resend_code': resend_code})


def forget(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        data = {'email': email}
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/verifyEmailOnly', json=data)
        if response.status_code == 200:
               request.session['email'] = email 
               return redirect('forget_password_verify')

    return render(request, 'login/forgetpass.html')

def forget_password_verify(request):
    email = request.session.get('email')
    if request.method == 'POST':
        code1 = request.POST.get('code1')
        code2 = request.POST.get('code2')
        code3 = request.POST.get('code3')
        code4 = request.POST.get('code4')
        combine = code1+code2+code3+code4
        data = {
          'email': email,
          'activation_code':int(combine)
        }
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/verifyEmail', json=data)
        if response.status_code == 200:
               request.session['email'] = email 
               return redirect('change_password')
        else:
               return redirect('forget_password_verify')
    return render(request, 'login/forgetpass_verify.html', {'email':email})
    

    
def change_password(request):
        email = request.session.get('email')
        if request.method == 'POST':
            password = request.POST.get('password')
            retype_password = request.POST.get('retype-password')
            if password == retype_password:
                data =  {
                  'email':email,
                  'password':str(password)
                }
                response = requests.post('https://thingsaccess.com/rfid/index.php/Api/setNewPassword', json=data)
                if response.status_code == 200:
                    return redirect('login_page')
  
        return render(request, 'login/changepassword.html')
    
 
def logout_page(request):
      # Clear the cache
      cache.clear()

    # Clear the relevant session data
      request.session.clear()

      logout(request)
      return render(request, 'login/login.html')

def bundle_details(request):
    complete_array = request.session.get('complete_bundle')
    total_array = request.session.get('totalBundle')
    progress_array = request.session.get('progress_bundle')
    faulty_array = request.session.get('faulty_bundle')
    # complete = len(complete_array)
    # total  =  len(total_array)
    # progress = len(progress_array)
    # faulty =  len(faulty_array)   
    data_artcile = get_article_data()
    return render(request, 'home/bundle_details.html',{'complete':complete_array,'total':total_array,'progress':progress_array,'faulty':faulty_array,'data_artcile':data_artcile})



def operator_details(request):
    global operator_info_state 
    # global data_dashboard
    operator_info_data = []
    for i in range(len(operator_info_state)):
        operator_info = operator_info_state[i]['operator_data']
        operator_info_data.append(operator_info) 

    total_operator = []
    active_op = []
    present_op = []
    absent_op = []


    for j in range(len(operator_info_data)):
        operator_status = operator_info_data[j]['status_id']
        if operator_status == '1':
            active_op.append(operator_status)
        elif operator_status == '2':
            present_op.append(operator_status)
        elif operator_status == '3':    
            absent_op.append(operator_status)
        total_operator.append(operator_status)


    total = len(total_operator)
    active_op  =  len(active_op)
    present = len(present_op)
    absent =  len(absent_op)   
    return render(request, 'home/operator_details.html',{'total':total,'active_op':active_op,'present':present,'absent':absent,'operator_info_data':json.dumps(operator_info_data)})



def machine_details(request):
    global machine_info_state
    print()
    total_machine = []
    idle_machine = []
    active_machine = []
    fault_machine = []
    powerdown_machine = []

    for i in range(len(machine_info_state)):
        totalMachine = machine_info_state[i]['state_id']
        if totalMachine == '1':
                idle_machine.append(totalMachine)
        elif totalMachine == '2':
                active_machine.append(totalMachine)
        elif totalMachine == '3':    
                fault_machine.append(totalMachine)
        elif totalMachine == '4':    
                powerdown_machine.append(totalMachine)
        total_machine.append(totalMachine)   


    total = len(total_machine)
    idle  =  len(idle_machine)
    active = len(active_machine)
    fault =  len(fault_machine)   
    powerdown =  len(powerdown_machine) 
    return render(request, 'home/machine_details.html',{'total':total,'idle':idle,'active':active,'fault':fault,'powerdown':powerdown,'machine_info_state':json.dumps(machine_info_state)})

def article_details(request):
    total_article =request.session.get('articleinfo')
    total_production = request.session.get('total_production', [])
    today_production = request.session.get('today_production', [])
    data_artcile = get_article_data()
    print(data_artcile,'artcileinfo')
    return render(request, 'home/article_details.html',{'total_article':total_article,'total_production':total_production,'today_production':today_production,'data_artcile':data_artcile})



def Add_operator(request):
   global operator_info_state
   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']
        print(data_article,'op')
        # Check if the operator was added successfully (you can customize this condition based on the response)
        if data_send['status'] == True:
            # Retrieve the current count from the session
            operators_info = request.session.get('operators_info', 0)

            # Increment the count by 1 since a new operator is added
            operators_info += 1

            # Save the updated count back to the session
            request.session['operators_info'] = operators_info
            data1 = {
                'id':data_article,
                'name': data_json.get('Name'),
                'cnic': data_json.get('cnic'),
                'cell': data_json.get('cell'),
                'address': data_json.get('address'),
                'skills': data_json.get('skill'),
                'tag_id': data_json.get('tag_id'),
                "timing": "00:00-00:00",
                "status_id": "2",
                "status": "Present",
                "created_on": "0000-00-00 00:00:00"
                
            }
            
            operator_data = { 

              'operator_data' : data1
            }

            operator_info_state.append(operator_data)
            print(operator_info_state, 'global')
            return JsonResponse({'data_article': data_article})
      
   return render(request, 'operators/addOperator.html',context={'skills':skills})


def Edit_Operator(request,id):
   global operator_info_state
   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'),  
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/editOperator', json=data)
         if response.status_code == 200:
                # Update the operator_info_state array with the new data
                operator_edit = response.json()
                operator_update = operator_edit['response']
                operator_index = None
                for i, operator in enumerate(operator_info_state):
                    if operator['operator_data']['id'] == id:
                        operator_index = i
                        break

                if operator_index is not None:
                    # If the operator is found, update its information with the new data
                    operator_info_state[operator_index]['operator_data'] = operator_update
                    print(operator_info_state,'global with edit')
                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):
   global operator_info_state
   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:
        operators_info = request.session.get('operators_info', 0)

            # Decrement the count by 1 since a new operator is added
        operators_info -= 1

            # Save the updated count back to the session
        request.session['operators_info'] = operators_info
        index_to_remove = 0
        for i, operator_data in enumerate(operator_info_state):
            if operator_data['operator_data']['id'] == str(id):
                index_to_remove = i
                break
        # print(index_to_remove,'id delete')
        operator_info_state.pop(index_to_remove)
        # print(operator_info_state,'update global with del')
        # print(index_to_remove,'del op')
        return redirect('operator_page')
        
        # messages.success(request, 'Data added successfully')
   else:
       return redirect('operator_page')
    #    return HttpResponse("Operator not deleted")


   
# machine 
def Add_Machine(request):
   global machine_info_state
   print(machine_info_state,'machine global',len(machine_info_state)) 
   skills = get_skill() 
   if request.method == 'POST':
      data_json = json.loads(request.body)    
      data = {
          'title': data_json .get('title'),
          'device_ID': data_json .get('device_ID'),
          'skill': data_json.get('skill')
          
      }
      response = requests.post('https://thingsaccess.com/rfid/index.php/Api/addMachine', json=data)
      data_send = response.json()
      data_machine = data_send['response']
      if data_send['status'] == True:
            # Retrieve the current count from the session
            machinesInfo = request.session.get('machinesInfo', 0)

            # Increment the count by 1 since a new operator is added
            machinesInfo += 1

            # Save the updated count back to the session
            request.session['machinesInfo'] = machinesInfo
            machine_add_list = {
                    "id":str(data_machine),
                    "machine_title": data_json.get('title'),
                    "device_ID": data_json.get('device_ID'),
                    "skill": data_json.get('skill'),
                    "created_on": "0000-00-00 00:00:00",
                    "state_id": "1",
                    "state_name": "Idle"
                
            }
            machine_info_state.append(machine_add_list)
            print(machine_info_state, 'global')
            return JsonResponse({'data_machine': data_machine})
      # if response.status_code != 200:
      #    # Insertion failed, show error message to user
      #    return HttpResponse("Machine not added successfully")
      # return redirect('machine_page')
   return render(request, 'machine/addMachine.html',context={'skills':skills})

def Edit_Machine(request,id):
   global machine_info_state
   skills = get_skill() 
   state = get_machine_state()    
   response = requests.get('https://thingsaccess.com/rfid/index.php/Api/getMachine')
   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'),
               'device_ID': request.POST.get('device_ID'),
               'state': request.POST.get('state'),
               'skill': request.POST.get('skill'),
         }
         response = requests.post('https://thingsaccess.com/rfid/index.php/Api/editMachine', json=data)
         if response.status_code == 200:
                machine_edit = response.json()
                machine_update = machine_edit['response']
                machine_index = None
                for i, machine in enumerate(machine_info_state):
                    if machine['id'] == id:
                        machine_index = i
                        break
               
                if machine_index is not None:
                    # If the operator is found, update its information with the new data
                    machine_info_state[machine_index]= machine_update
                    print(machine_info_state,'global with edit')
                return redirect('machine_page')
               # messages.success(request, 'Data added successfully')
         else:
                 return redirect('machine_page')
               # Insertion failed, show error message to user
            #    messages.error(request, 'Failed to edit data')

   return render(request,'machine/editMachine.html',context={'item': edit_item,'skills':skills,'state':state})
  
def delete_Machine(request,id):
    global machine_info_state
    data_delete = {
        'id': id
    }
    print(data_delete)
    response = requests.post('https://thingsaccess.com/rfid/index.php/Api/deleteMachine', json=data_delete)
    if response.status_code == 200:
            machinesInfo = request.session.get('machinesInfo', 0)
                # Decrement the count by 1 since a new operator is added
            machinesInfo -= 1
                # Save the updated count back to the session
            request.session['machinesInfo'] = machinesInfo
            index_to_remove = 0
            for i, machine_data in enumerate(machine_info_state):
                if machine_data['id'] == str(id):
                    index_to_remove = i
                    break
            # print(index_to_remove,'id delete')
            machine_info_state.pop(index_to_remove)
            print(machine_info_state,'with del')
            return redirect('machine_page')
    else:
        return redirect('machine_page')