from flask import current_app
import requests
from ownchatbot.user_handlers import award_chat_points
import random


def get_client_id(user_id):
    owncast_url = current_app.config['OWNCAST_URL']
    access_token = current_app.config['ACCESS_TOKEN']
    url = f'{owncast_url}/api/integrations/moderation/chat/user/{user_id}'
    auth_bearer = f'Bearer {access_token}'
    headers = {'Authorization': auth_bearer}
    try:
        response = requests.get(url, headers=headers)
        response = response.json()
        if response["connectedClients"]:  # Make sure this is an actual, connected client
            client_id = response['connectedClients'][0]['id']
            current_app.logger.debug(f'Got client id {client_id}')
            return client_id
        else:
            current_app.logger.info('Not a connected client. Can\'t get client ID.')
            return False
    except requests.exceptions.RequestException as gcierror:
        current_app.logger.error(f'Couldn\'t get client id from Owncast: {gcierror}')
        return False


def live_now():  # Check if stream is live
    owncast_url = current_app.config['OWNCAST_URL']
    if owncast_url != '':  # If owncast URL is set, award points
        url = f'{owncast_url}/api/status'
        try:
            response = requests.get(url)
            if response.json()['online']:
                return True
            else:
                return False
        except requests.exceptions.RequestException as cserror:
            current_app.logger.error(f'Couldn\'t check if stream is live: {cserror}')
            return False
    else:
        current_app.logger.error('Owncast url is not set. Can\'t check if stream is live.')
        return False


def award_points(db):  # Award points to users
    owncast_url = current_app.config['OWNCAST_URL']
    access_token = current_app.config['ACCESS_TOKEN']
    url = f'{owncast_url}/api/integrations/clients'
    auth_bearer = f'Bearer {access_token}'
    headers = {'Authorization': auth_bearer}
    try:
        response = requests.get(url, headers=headers)
    except requests.exceptions.RequestException as aperror:
        current_app.logger.error(f'Couldn\'t get user info: {aperror}')
        return
    if response.status_code != 200:
        current_app.logger.error(f'Couldn\'t award points: {response.status_code}.')
        return
    unique_users = set(map(lambda user_object: user_object['user']['id'], response.json()))
    for user_id in unique_users:
        award_chat_points(db, user_id, current_app.config['POINTS_AWARD'])


def send_chat(message):  # Send message to owncast chat
    owncast_url = current_app.config['OWNCAST_URL']
    access_token = current_app.config['ACCESS_TOKEN']
    url = f'{owncast_url}/api/integrations/chat/send'
    auth_bearer = f'Bearer {access_token}'
    headers = {'Authorization': auth_bearer}
    try:
        response = requests.post(url, headers=headers, json={'body': message})
    except requests.exceptions.RequestException as scerror:
        current_app.logger.error(f'Couldn\'t send \"{message}\" to Owncast: {scerror}')
        return
    if response.status_code != 200:
        current_app.logger.error(f'Couldn\'t send \"{message}\" to Owncast: {response.status_code}.')
        return
    return response.json()


def send_private_chat(user_id, message):
    client_id = get_client_id(user_id)
    if client_id or client_id == 0:  # If no client ID is found, don't try to send
        owncast_url = current_app.config['OWNCAST_URL']
        access_token = current_app.config['ACCESS_TOKEN']
        url = f'{owncast_url}/api/integrations/chat/system/client/{client_id}'
        auth_bearer = f'Bearer {access_token}'
        headers = {'Authorization': auth_bearer}
        try:
            response = requests.post(url, headers=headers, json={'body': message})
        except requests.exceptions.RequestException as swerror:
            current_app.logger.error(f'Couldn\'t send \"{message}\" to Owncast: {swerror}')
        except Exception as swerror:
            current_app.logger.error(f'Couldn\'t send \"{message}\" to Owncast: {swerror}')
        if response.status_code != 200:
            current_app.logger.error(f'Couldn\'t send \"{message}\" to Owncast: {response.status_code}.')
    else:
        current_app.logger.info(f'Couldn\'t send \"{message}\" to Owncast. Not a connected client.')


def send_system_chat(message):
    owncast_url = current_app.config['OWNCAST_URL']
    access_token = current_app.config['ACCESS_TOKEN']
    url = f'{owncast_url}/api/integrations/chat/system'
    auth_bearer = f'Bearer {access_token}'
    headers = {'Authorization': auth_bearer}
    try:
        response = requests.post(url, headers=headers, json={'body': message})
    except requests.exceptions.RequestException as swerror:
        current_app.logger.error(f'Couldn\'t send {message} to Owncast: {swerror}')
        sys.exit()
    if response.status_code != 200:
        current_app.logger.error(f'Couldn\'t send {message} to Owncast: {response.status_code}.')
        sys.exit()
    response = response.json()
