from django.shortcuts import render
from django.shortcuts import redirect
from django.http import JsonResponse
import requests
import pandas as pd
import json
import numpy as np
# Create your views here.

def get_reporting(request):
    
    return render(request,"reporting/reporting.html")

def reporting_result(request):
    response = requests.get('https://thingsaccess.com/rfid/index.php/Api/qualityReporting')
    print(response)
    return JsonResponse(response.json())

def filterArticleReporting(request):
    return render(request,"reporting/fitlerArticleReporting.html")

def filterArticleData(request):
    data = json.loads(request.body)
    print(request.session['articleinfo'])
    json_article_info = json.dumps(request.session['articleinfo'],indent=2)
    read_json = pd.read_json(json_article_info)
    read_json = read_json.reset_index(drop=True)
    filtered_results = pd.DataFrame()
    for articles in data["articleColumn"]:
        filter_json = read_json[read_json["article_name"]==articles]
        filtered_results = pd.concat([filtered_results,filter_json[data["articleData"]]])
    get_data = filtered_results.to_dict(orient='records')
    json_data = json.dumps(get_data,indent=2)
    print(type(get_data))
    return JsonResponse({'get_data':get_data})



def filterOperatorData(request):
    data = json.loads(request.body)
    print(type(request.session['operatorsInfo']))
    operator_json = []
    for i in range(len(request.session['operatorsInfo'])):
        operator_json.append({"id":request.session['operatorsInfo'][i]["operator_data"]['id'],
                              "name":request.session['operatorsInfo'][i]["operator_data"]['name'],
                              "cnic":request.session['operatorsInfo'][i]["operator_data"]['cnic'],
                              "cell":request.session['operatorsInfo'][i]["operator_data"]['cell'],
                              "address":request.session['operatorsInfo'][i]["operator_data"]['address'],
                              "skills":request.session['operatorsInfo'][i]["operator_data"]['skills'],
                              "tag_id":request.session['operatorsInfo'][i]["operator_data"]['tag_id'],
                              "timing":request.session['operatorsInfo'][i]["operator_data"]['timing'],
                              "status_id":request.session['operatorsInfo'][i]["operator_data"]['status_id'],
                              "status":request.session['operatorsInfo'][i]["operator_data"]['status'],
                              "wage":request.session['operatorsInfo'][i]["operator_data"]['wage'],
                              "created_on":request.session['operatorsInfo'][i]["operator_data"]['created_on'],
                              })
    json_article_info = json.dumps(operator_json,indent=2)
    read_json = pd.read_json(json_article_info)
    read_json = read_json.reset_index(drop=True)
    filtered_results = pd.DataFrame()
    read_json["id"] = read_json["id"].astype(str)

    for articles in data["articleColumn"]:
        filter_json = read_json[read_json["id"]==articles]
        print("filter_json",filter_json)
        filtered_results = pd.concat([filtered_results,filter_json[data["articleData"]]])
        print(filtered_results)
    get_data = filtered_results.to_dict(orient='records')
    print(get_data)
    for item in get_data:
        for key, value in item.items():
            if isinstance(value, float) and np.isnan(value):
                item[key] = None

    json_data = json.dumps(get_data, indent=2)
    print(json_data)
    return JsonResponse({'get_data':get_data})

def Get_production_report(request):
   print(request)
   if request.method == 'POST':
        data = json.loads(request.body)
        data_skill = {
            'article_id': data.get('id'),
            'reportType': str(data.get('reportType')),
            'date': data.get('date'),
        }
        # Convert data_skill to raw format if needed
        raw_data = "\n".join([f"{key}: {value}" for key, value in data_skill.items()])
        print(data_skill)
        headers = {'Content-Type': 'application/json'}
        response = requests.post('https://thingsaccess.com/rfid/index.php/Api/productionReport', json=data_skill,headers=headers)
        data_send = response.json()
        data_skill = data_send['response']
        print(data_skill)
        return JsonResponse({'data_skill': data_skill})
   
def Get_operators_report(request):
       print(request)
       if request.method == 'POST':
            data = json.loads(request.body)
            data_skill = {
                'operator_id': data.get('id'),
                'reportType': str(data.get('reportType')),
                'startDate': data.get('start_date'),
                'endDate': data.get('end_date'),
            }
            # Convert data_skill to raw format if needed
            raw_data = "\n".join([f"{key}: {value}" for key, value in data_skill.items()])
            print(data_skill)
            headers = {'Content-Type': 'application/json'}
            response = requests.post('https://thingsaccess.com/rfid/index.php/api/wageCalculation', json=data_skill,headers=headers)
            data_send = response.json()
            data_skill = data_send['response']
            print(data_skill)
            return JsonResponse({'data_skill': data_skill})