from django.http import JsonResponse
# from django.views import View
import requests
import json
# import pandas as pd
from django.views.decorators.csrf import csrf_exempt
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__)))
import LogUtils

logger = LogUtils.getRootLogger()

def get_token(client_id, client_secret, tenant_id, resource):
    token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/token"
    payload = {
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_secret": client_secret,
        "resource": resource,
    }
    response = requests.post(token_url, data=payload)
    if response.status_code == 200:
        return response.json().get("access_token")
    else:
        raise Exception(f"Failed to retrieve token: {response.text}")
        
        
# Variables
client_id = "6a77dbc5-5110-4b3f-85cf-692520941150"
client_secret = "mzyHgqNa=I[:D3Ygq_OtuVhRKlcvb776"
tenant_id = "95f69e7d-1811-4ab9-9b5a-eba95d3eba9b"
base_url = "https://api.businesscentral.dynamics.com/"

resource = f"{base_url}"

@csrf_exempt
def update_companycode(request):
    try:
        response1={}
        if request.method == "POST":
            data = json.loads(request.body)
            print('data',data)
            # Get token

            bc_invoice_id = data.get("Document_No")
            unit_pr = data.get("Unit_price")
            quantity = data.get("Quantity")
            product_id = data.get("Product_Id")
            descrip='ACAD'
            
            # bc_invoice_id = request.POST.get("Document_No")
            print('bc_invoice_id',bc_invoice_id)
            # unit_pr = request.POST.get("Unit_price")
            # quantity = request.POST.get("Quantity")
            # Product_id = request.POST.get("Product_Id")

            
            token = get_token(client_id, client_secret, tenant_id, resource)
            logger.info('token authenticated')
            
            headers = {
                'Content-Type': 'application/json',
                "Authorization": "Bearer " + token,
                # "If-Match": etag,  # Required for concurrency control
                "Prefer": "odata.maxpagesize=5000",
                "OData-MaxVersion": "4.0",
                "OData-Version": "4.0",
            }
            
            
            third_api_url = base_url + f"/v2.0/95f69e7d-1811-4ab9-9b5a-eba95d3eba9b/Production/ODataV4/Company('PROD-NAIER')/SalesInvLines?$filter=Document_No eq '{bc_invoice_id}' and No eq '{product_id}' and Description eq '{descrip}'"

            # third_api_url = base_url + f"/v2.0/95f69e7d-1811-4ab9-9b5a-eba95d3eba9b/CEDEV_DONOTDELETE/ODataV4/Company('DEV-121219')/SalesInvLines?$filter=Document_No eq '{bc_invoice_id}' and No eq '{product_id}' and Description eq '{descrip}'"

            thi_records = []
            
            while third_api_url:
                response = requests.get(third_api_url, headers=headers)
                data = response.json()
                thi_records.extend(data["value"])
                third_api_url = data.get("@odata.nextLink")
            
           
            print(len(thi_records))
            print("data retrived")
            logger.info('len of record %s'%len(thi_records))
            
            for record in thi_records:
                # if record.get("Document_No") == bc_invoice_id and record.get("No") == product_id and record.get("Description") == "Academy Fellows Membership":
                    # Use Document_No and Line_No for the update URL
                if record.get("No") == product_id:
                    print('recored have')
                    etag = record.get("@odata.etag")
                    # document_no = record.get("Document_No")
                    line_no = record.get("Line_No")
                    # print('document_no',document_no)
                    print('line_no',line_no)
                    # Ensure both fields exist before proceeding
                    logger.info('bc_invoice_id  %s'%bc_invoice_id)

                    if bc_invoice_id and line_no is not None:
                        logger.info('line_no record  %s'%line_no)
                        
                        # Prepare the update payload
                        
                        # third_api_url = base_url + "/v2.0/95f69e7d-1811-4ab9-9b5a-eba95d3eba9b/Production/ODataV4/Company('PROD-NAIER')/SalesInvLines"

                        # url = f"{base_url}/v2.0/95f69e7d-1811-4ab9-9b5a-eba95d3eba9b/CEDEV_DONOTDELETE/ODataV4/NAV.SalesInvLines(Document_Type='Invoice',Document_No='{bc_invoice_id}',Line_No={line_no})"
                        url = f"{base_url}/v2.0/95f69e7d-1811-4ab9-9b5a-eba95d3eba9b/Production/ODataV4/Company('PROD-NAIER')/SalesInvLines(Document_Type='Invoice',Document_No='{bc_invoice_id}',Line_No={line_no})"

                        data = {
                            # "Description": "Academy Fellows Membership",
                            "Shortcut_Dimension_1_Code": "13",
                            "Unit_Price": unit_pr,
                            "Quantity":quantity
                        }
                        
                        headers['If-Match'] = etag
            
                        
                        # Make the PATCH request
                        response1 = requests.patch(url, headers=headers, data=json.dumps(data))
                        logger.info('updated record now  %s'%bc_invoice_id)

            # Check the response
            if response1:
                # print(response1)
                if response1.status_code == 200:
                    print("Record updated successfully.")
                    return JsonResponse({"response":'updated successfully'})

                else:
                    print('error')
                    logger.info('error record  %s'%response1.text)
                    return JsonResponse({"response":response1.text})
            else:
                print("No record found")
                return JsonResponse({"response":'No record found'})
        elif request.method == "GET":
            return JsonResponse({"response":'Nothing to be processed'})

    except Exception as e:
        return JsonResponse({"error": str(e)})
        logger.info('error record  %s'%e)
    
    

            