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 operators.views import get_operator_data
import base64
import datetime


User = get_user_model()

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

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

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



def login_page(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        image_data = ''
        image_path  = r'C:\Users\Lenovo\Downloads\rfid_django_1\rfid_django_1\core\static\img\thingzxcess-logo.png'
        with open( image_path, 'rb') as image_file:
            image_data = base64.b64encode(image_file.read()).decode('utf-8')

        

        request.session["entered_email"] = email

        if email == "":
             messages.error(request,"Please enter email")
        elif password == "":
            messages.error(request,"Please enter password")
        else:
           data = {'email': email, 'password': password}
           headers = {'Content-Type': 'application/json'}
           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']

            complete_bundle = []
            totalBundle = []
            progress_bundle = []
            faulty_bundle = []    
                       
                
           
            
         
           
            
            operator_info_data = []
            operator_info_state = data_dashboard['operatorsInfo']
            
            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 = []
            request.session['operator_info_data'] = operator_info_data
       

            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)
           
           
            request.session['total_operator'] = total_operator
            request.session['active_op'] = active_op   
            request.session['present_op'] = present_op 
            # request.session['absent_op'] = absent_op 
            request.session['img_base'] = str(image_data)

            total_machine = []
            idle_machine = []
            active_machine = []
            fault_machine = []
            powerdown_machine = []
            machine_info_state = [] 
            
            
           
           
            # 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()
            op_abesent = []
            # 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['articlesInfo']
                request.session['complete_bundle'] = 0 if data_dashboard['bundlesInfo']['completed'] is None else data_dashboard['bundlesInfo']['completed']
                request.session['totalBundle'] = 0 if data_dashboard['bundlesInfo']['total']  is None else data_dashboard['bundlesInfo']['total']
                request.session['progress_bundle'] = 0 if data_dashboard['bundlesInfo']['inProgress'] is None else data_dashboard['bundlesInfo']['inProgress']
                request.session['faulty_bundle'] = 0 if data_dashboard['bundlesInfo']['qualityError'] is None else data_dashboard['bundlesInfo']['qualityError']
                request.session['faulty_bundle1'] = 0 if data_dashboard['bundlesInfo']['qualityError'] is None else data_dashboard['bundlesInfo']['qualityError']
                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
                request.session ['failedBundlesWRTarticles'] = data_dashboard['failedBundlesWRTarticles']
                print(data_dashboard['failedBundlesWRTarticles'])
                request.session["operatorsInfo"] = data_dashboard["operatorsInfo"]
                for i in range(len(data_dashboard["operatorsInfo"])):
                    if data_dashboard["operatorsInfo"][i]["operator_data"]["status_id"] == '3':
                        op_abesent.append(data_dashboard["operatorsInfo"][i]["operator_data"])
                request.session['absent_op'] = op_abesent
                print(op_abesent)
                #commented by me
                # total_production = data_dashboard['articlesInfo'][0]['total_production']
                # today_production = data_dashboard['articlesInfo'][0]['today_production']
                # request.session['total_production'] = total_production
                # request.session['today_production'] = today_production
                # request.session['operators_info'] = data_dashboard['activeOperators']
                # request.session['bundlesInfo'] = data_dashboard['bundleInProgress']
                # request.session['machinesInfo'] = data_dashboard['activeMachines']
                request.session['machinesInfo'] = data_dashboard['machinesInfo']
                # completed_articles = 0
                completed_articles = data_dashboard["articlesStatesCount"]["totalArticles"] - data_dashboard["articlesStatesCount"]["inProgressArticles"]
                request.session["total_article_count"] = data_dashboard["articlesStatesCount"]["totalArticles"]
                request.session["active_article_count"] = data_dashboard["articlesStatesCount"]["inProgressArticles"]
                request.session["completed_article"] = data_dashboard["articlesStatesCount"]["completedArticles"]
                # if data_dashboard['articleInProgress'] !=None:
                #     article_percent = completed_articles/data_dashboard["articlesStatesCount"]["totalArticles"] * 100
                #     # request.session ['active_article_count'] = data_dashboard['articleInProgress']
                #     # request.session ['total_article_count'] = data_dashboard['articleThisMonth']
                #     request.session ['article_percent'] = round(article_percent)
                # else:
                #     request.session ['active_article_count'] = 0
                #     request.session ['total_article_count'] = 0
                #     request.session ['article_percent'] = 0
                    # if else comment for error checking....
                # if data_dashboard['bundleThisMonth'] !=None:
                #     request.session ['active_bundle_count'] = data_dashboard['bundleInProgress']
                #     request.session ['total_bundle_count'] = data_dashboard['bundleThisMonth']
                #     completedBundle = data_dashboard['bundleThisMonth'] - data_dashboard['bundleInProgress']
                #     request.session ['completedBundle'] = completedBundle
                #     bundle_percent = completedBundle/data_dashboard['bundleThisMonth']*100
                #     request.session ['bundle_percent'] = round(bundle_percent)
                # else:
                #     request.session ['active_bundle_count'] = 0
                #     request.session ['total_bundle_count'] = 0
                #     bundle_percent = 0
                #     request.session ['bundle_percent'] = 0
                #     request.session ['completedBundle'] = completedBundle  
                               

                request.session ['active_operators_count'] = data_dashboard['activeOperators']
                request.session ['total_operators_count'] = data_dashboard['operatorsTotalCount']
                operator_percent = data_dashboard['activeOperators']/data_dashboard['operatorsTotalCount']*100
                request.session ['operator_percent'] = round(operator_percent)

                request.session ['active_machine_count'] = 0 if data_dashboard['activeMachines'] is None else data_dashboard['activeMachines']
                request.session ['total_machine_count'] = data_dashboard['machineTotalCount']
                if data_dashboard['activeMachines'] and data_dashboard['machineTotalCount'] is not None:
                    machine_percent = data_dashboard['activeMachines']/data_dashboard['machineTotalCount']*100
                    request.session ['machine_percent'] = round(machine_percent)
                else:
                    request.session ['machine_percent'] = 0
                # request.session ["bundlesDataGraph"] = data_dashboard["completedAndIncompletedBundles"]
                request.session ['bundleGraphData'] = data_dashboard['completedAndIncompletedBundles']
                request.session ['activeOperatorsCountMonthly'] = data_dashboard['activeOperatorsCountMonthly']
                request.session ['completedBundlesWRTarticles'] = data_dashboard['completedBundlesWRTarticles']

                
                dataArray = []
                request.session ['operatorActiveInactiveTime'] = dataArray

            except (KeyError, IndexError):
                request.session ['article_percent'] = 0
                request.session['articleinfo'] = 0
                request.session['operators_info'] = 0
                request.session['bundlesInfo'] = 0
                request.session['machinesInfo'] = []  
                request.session ['active_article_count'] = 0
                request.session ['total_article_count'] = 0
                request.session ['active_bundle_count'] = 0
                request.session ['total_bundle_count'] = 0

                request.session ['active_operators_count'] = 0
                request.session ['total_operators_count'] = 0

                request.session ['active_machine_count'] = 0
                request.session ['total_machine_count'] = 0
                request.session ['operatorActiveInactiveTime'] = []
                request.session ['failedBundlesWRTarticles'] = []
                request.session ['activeOperatorsCountMonthly'] = {}
                request.session ['completedBundlesWRTarticles'] = []
                request.session["today_date"] = datetime.date.today
            
            return redirect('home')
           else:
            data = response.json()
            error = data["response"]
            if error == -121:
                 messages.error(request, 'Incorrect password')
            elif error == -14:
                messages.error(request,"User account blocked")
            elif error == -13:
                messages.error(request,"Email not verified")
            elif error == -120:
                messages.error(request,"Email not found")
            elif error == -12:
                messages.error(request,"Missing information")
            else:
                messages.error(request,"Missing information")
            
            # return render(request, 'login/login.html')
            # if response.status_code == 401:
            #     data = response.json()
            #     error = data['response']
            #     if error == '-121':
            #             invalidpass = 'Invalid password'
            # return HttpResponse("login not")
            # return HttpResponse(response)
            
            # messages.error(request, 'failed to login')  
        

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

def home(request):
    # Retrieve session data
    articleinfo = request.session.get('articleinfo')
    operators_info = request.session.get('operators_info')
    bundlesInfo = request.session.get('bundlesInfo')
    machinesInfo = request.session.get('machinesInfo')
    
    return render(request, 'home/index.html', {'articleinfo': articleinfo, 'operators_info': operators_info, 'bundlesInfo': bundlesInfo, 'machinesInfo': machinesInfo})
    
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 
               return redirect('email_verify')
               # messages.success(request, 'Data added successfully')
         else:
             messages.error(request, 'Failed to sign up')  # Display error message
             return redirect('signup_page')
               
            #    messages.error(request, 'Failed to edit data')
    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):
      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_bundle1', [])
    complete = complete_array
    total  =  total_array
    progress = progress_array
    faulty =  faulty_array  
    data_artcile = get_article_data()
    return render(request, 'home/bundle_details.html',{'complete':complete,'total':total,'progress':progress,'faulty':faulty,'data_artcile':data_artcile})



def operator_details(request):
    total_operator = request.session.get('total_operators_count', [])
    active_op = request.session.get('active_operators_count', [])
    present_op = request.session.get('present_op', [])
    absent_op = request.session.get('absent_op', [])
    operator_info_data = request.session.get('operator_info_data',[])
    total = total_operator
    active_op  =  active_op
    present = len(present_op)
    absent =  len(absent_op) 
    operatorData = get_operator_data()
    print("operator_info_data",operator_info_data)  
    return render(request, 'home/operator_details.html',{'total':total,'active_op':active_op,'present':present,'absent':absent,'operator_info_data':operatorData})

def machine_details(request):
    total_machine = request.session.get('total_machine', [])
    idle_machine = request.session.get('idle_machine', [])
    active_machine = request.session.get('active_machine', [])
    fault_machine = request.session.get('fault_machine', [])
    powerdown_machine = request.session.get('powerdown_machine', [])
    machine_info_state = request.session.get('machine_info_state', [])
    machineInfo = request.session.get('machinesInfo',[])
    power_down =[]
    active = []
    Idles = []
    Faults = []

    if len(machineInfo)>0:
        for i in range(len(machineInfo)):
            if machineInfo[i]["state_name"] == "Power down":
                power_down.append(machineInfo)
            if machineInfo[i]["state_name"] == "Active":
                active.append(machineInfo)
            if machineInfo[i]["state_name"] == "Idle":
                Idles.append(machineInfo)
            if machineInfo[i]["state_name"] == "Fault":
                Faults.append(machineInfo)
    
    total = len(machineInfo)
    idle  =  len(Idles)
    active = len(active)
    fault =  len(Faults)   
    powerdown =  len(power_down) 
    return render(request, 'home/machine_details.html',{'total':total,'idle':idle,'active':active,'fault':fault,'powerdown':powerdown,'machine_info_state':json.dumps(machineInfo)})

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

