import requests
from django.shortcuts import render, redirect
import uuid
from django.http import HttpResponse
from django.http import JsonResponse
import logging
import pymysql
import pandas as pd
import logging
import sshtunnel
from sshtunnel import SSHTunnelForwarder
from sshtunnel import SSHTunnelForwarder
import random
import string

logger = logging.getLogger('login_page') 

logger.debug('Test debug message')

def generate_authorization_code():
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=16))

def get_authorization_code(request):
    code = generate_authorization_code()
    return JsonResponse({'authorization_code': code})
    # if request.method == 'GET':
    #     authorization_code = generate_authorization_code()
    #     return JsonResponse({'authorization_code': authorization_code})
    # else:
    #     return JsonResponse({'error': 'Invalid request method'}, status=400)

def show(request):
    # username = request.session.get('username')
    return render(request, 'homepage.html')

def login(request):
    error_message = None  # Initialize error_message
    if request.method == 'POST':
        # Get user credentials from POST request
        username = request.POST['email']
        password = request.POST['password']
        
        # Send POST request to API with user credentials
        data = {
            'email': username,
            'password': password,
        }
        response = requests.post('https://thingsxess.com/has/index.php/apis/login', data=data)
        
        
        # Handle response from API
        if response.status_code == 200:
            data_send = response.json()
            login_data = data_send['response']
            # email =  login_data['userInfo'][0]['email']
            email_data =  login_data['userInfo']['email']
            request.session['email_data'] = email_data
            logger.debug(f"login_response: {email_data}")
            # logger.debug(f"login_response email: {email}")
            # Assuming the API returns a JSON response with a token field
            # token = response.json().get('token')
            token = '1234567'
            print(token,'aqsa')

            if token:
                # Store the token in the session
                request.session['token'] = token
                # authorization_code = generate_authorization_code()
                # request.session['authorization_code'] = authorization_code
                # response = requests.get('https://thingsaccess.com/alexa/api/get-authorization-code/')
    
                # if response.status_code == 200:
                #     authorization_code = response.json().get('authorization_code')
                #     request.session['authorization_code'] = authorization_code
                
                # Redirect to your custom account linking URL
                authorization_uri = "https://www.amazon.com/ap/oa"
                response_type = "code"
                client_id = "amzn1.application-oa2-client.d0934e932dbb4233a3cc853f4be611f1"
                redirect_uri = "https://thingsaccess.com/alexa/callback"
                state = "xyz123"
                amazon_redirect_url = f"{authorization_uri}?response_type={response_type}&client_id={client_id}&redirect_uri={redirect_uri}&state={state}&scope=profile"
                return redirect(amazon_redirect_url)
        
            else:
                error_message = 'Unable to retrieve token. Please try again.'
                # logger.debug(error_message)
                return render(request, 'login.html', {'error_message': error_message})
        else:
            # Login failed, display error message
            error_message = 'Invalid credentials. Please try again.'
            # logger.debug(error_message)
            return render(request, 'login.html', {'error_message': error_message})
    else:
        # Display login page
        return render(request, 'login.html')


# def account_linking(request):
#     token = request.session.get('token')
#     return render(request, 'account_linking.html',context={'token':token})


def exchange_authorization_code(authorization_code):
    client_id = "amzn1.application-oa2-client.d0934e932dbb4233a3cc853f4be611f1"
    client_secret = "amzn1.oa2-cs.v1.b2e29379c7f0c92058accca3856b9d7223bc6c75dce39f28638df39d23537614"
    redirect_uri = "https://thingsaccess.com/alexa/callback"
    
    data = {
        'grant_type': 'authorization_code',
        'code': authorization_code,
        'client_id': client_id,
        'client_secret': client_secret,
        'redirect_uri': redirect_uri,
    }
    
    token_url = "https://api.amazon.com/auth/o2/token"
    response = requests.post(token_url, data=data)
    response_type = response.json()
    logger.debug(f"amaozn_response: {response_type}")
    print(response ,'r')
    return response


def alexa_callback(request):
    if 'code' in request.GET:
        authorization_code = request.GET['code']
        
        # Exchange authorization code for access token
        token_response = exchange_authorization_code(authorization_code)
        if token_response.status_code == 200:
            access_token = token_response.json().get('access_token')
            logger.debug(f"access token: {access_token}")
            if access_token:
                # Fetch user profile using the access token
                profile_response = get_user_profile(access_token)
                if profile_response.status_code == 200:
                    user_profile = profile_response.json()
                    user_id = user_profile.get('user_id')  # Adjust the field name as per Login with Amazon's response
                    email_info = request.session.get('email_data')
                    logger.debug(f"user_id from profile: {user_id}")
                    # Store the user_id in your database
                    save_user_id_to_database(user_id,email_info)
                    # skill_id = '555a13b9-3419-4128-a869-0ea2d492f655'  # Replace with your skill's ID
                    # redirect_url = f'https://alexa.amazon.com/api/skills/amzn1.ask.skill.555a13b9-3419-4128-a869-0ea2d492f655/enablement'
                    # return redirect(redirect_url)
                    # Create a JSON response indicating successful account linking
                    response_data = {
                        "response": {
                            "outputSpeech": {
                                "type": "PlainText",
                                "text": "Your account has been successfully linked."
                            },
                            "card": {
                                "type": "LinkAccount"
                            },
                            "shouldEndSession": False  
                        }
                    }
                    
                    return JsonResponse(response_data)
                else:
                    response_content = f"Failed to fetch user profile. Response: {profile_response.content.decode('utf-8')}"
                    return HttpResponse(response_content)
            else:
                response_content = "Access token not found in response."
                return HttpResponse(response_content)
        else:
            response_content = f"Token exchange failed. Response: {token_response.content.decode('utf-8')}"
            return HttpResponse(response_content)
    else:
        return HttpResponse("Invalid authorization code.")
    
# def enable_alexa_skill(user_id, access_token):
#     endpoint = "https://api.amazonalexa.com"  # You can change this endpoint based on your region
#     headers = {
#         "Authorization": f"Bearer {access_token}",
#         "Content-Type": "application/json"
#     }
#     payload = {
#         "skillId": "amzn1.ask.skill.555a13b9-3419-4128-a869-0ea2d492f655"  # Replace with your actual skill ID
#     }
#     enable_url = f"{endpoint}/v1/users/{user_id}/skills/amzn1.ask.skill.555a13b9-3419-4128-a869-0ea2d492f655/enablement"
#     response = requests.put(enable_url, headers=headers, json=payload)
#     return response    
    


def get_user_profile(access_token):
    profile_url = "https://api.amazon.com/user/profile"
    headers = {"Authorization": f"Bearer {access_token}"}
    response = requests.get(profile_url, headers=headers)
    return response



ssh_host = '142.132.186.119'
ssh_username = 'root'
ssh_password = 'qh4IZjMro4q&*5N'
database_username = 'root'
database_password = 'PG@admin123$'
database_name = 'smarthome_db'
localhost = '127.0.0.1'
# port='22022'

def open_ssh_tunnel(verbose=False):
    try:
        if verbose:
            pass
            # sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG

        global tunnel
        tunnel = SSHTunnelForwarder(
            (ssh_host, 22),
            ssh_username = ssh_username,
            ssh_password = ssh_password,
            remote_bind_address = ('127.0.0.1', 3306)
        )

        tunnel.start()
        # print("tunnel connection successfully created")
    except BaseException as e:
        logger.debug("Error while connecting to tunnel", e)

    # print(tunnel)

def mysql_connect():
    """Connect to a MySQL server using the SSH tunnel connection
    
    :return connection: Global MySQL database connection
    """
    try:
        global connection

        connection = pymysql.connect(
            host='127.0.0.1',
            user=database_username,
            passwd=database_password,
            db=database_name,
            port=tunnel.local_bind_port
        )
        # print("mysql connected successfuly")
    except BaseException as e:
        logger.debug("Error while connecting to MySQL", e)
def run_query(sql):
        return pd.read_sql_query(sql, connection)

def mysql_disconnect():
    """Closes the MySQL database connection.
    """
    connection.close()
def close_ssh_tunnel():
    """Closes the SSH tunnel connection.
    """ 
    tunnel.close

def save_user_id_to_database(user_id,email_info):
    # Open SSH tunnel and connect to MySQL
    open_ssh_tunnel()
    mysql_connect()
    
    try:
        # Assuming 'users' is the name of your table
        # Replace 'alexahashid' with the actual column name
        # Assuming 'email' is the user's email (change this to match your schema)

        update_query = f"UPDATE Users SET Hash_alexaId = '{user_id}' WHERE email = '{email_info}'"
        with connection.cursor() as cursor:
            cursor.execute(update_query)
        connection.commit()
    except BaseException as e:
        logger.debug("Error while updating database:", e)
    
    # Disconnect from MySQL and close SSH tunnel
    mysql_disconnect()
    close_ssh_tunnel()




# def exchange_token(request):
#     # Get the stored username from the session
#     username = request.session.get('username')
#     token = request.session.get('token')
#     if username:
#         # You might need to modify the following code based on Ride Hailer's API requirements
#         token_url = 'https://ridehailer.com/token'  # Replace with Ride Hailer's token endpoint
#         client_id = 'your_client_id'  # Replace with your Ride Hailer client ID
#         client_secret = 'your_client_secret'  # Replace with your Ride Hailer client secret
        
#         token_data = {
#             'grant_type': 'password',  # Use the appropriate grant type for your scenario
#             'username': username,
#             'password': 'user_password',  # Replace with the user's password
#             'client_id': client_id,
#             'client_secret': client_secret,
#         }
        
#         response = requests.post(token_url, data=token_data)
        
#         if response.status_code == 200:
#             access_token = response.json().get('access_token')
            
#             # Store the access token in the session for future use
#             request.session['access_token'] = access_token
            
#             return redirect('home')  # Redirect the user to the home page
#         else:
#             # Handle token exchange failure
#             error_message = 'Token exchange failed. Please try again.'
#             return render(request, 'error.html', {'error_message': error_message})
#     else:
#         # Handle the case where username is not found in the session
#         error_message = 'User not authenticated.'
#         return render(request, 'error.html', {'error_message': error_message})