from flask import current_app
from sqlite3 import Error
from ownchatbot.db import get_db
from ownchatbot.user_handlers import get_id_by_email, award_chat_points, add_email_to_points, get_all_users_with_user_id
from ownchatbot.owncast_com import send_chat, send_private_chat
from ownchatbot.bot_messages import porps
from ownchatbot.reward_handlers import save_alerts
import json
import os


def accept_donation(donation_info, donation_points, donation_service):
    try:
        db = get_db()
        alerts_dict = current_app.config['ALERTS']
        is_public = donation_info[0]
        email = donation_info[2]
        amount = donation_info[3]
        amount = int(float(amount))  # Convert from str to int
        message = donation_info[4]
        points = amount * donation_points  # Multiply by streamers donation points award
        ids = get_id_by_email(db, email)
        if not ids:  # If no id found with that email address
            if add_email_to_points(db, email, points):  # Create empty account with email and points
                name = 'Someone'
                alerts_dict['gb_name'] = 'New Donation!'
                current_app.logger.info(f'No user with email \"{email}\" found in database, created empty account.')
        else:  # Grant points to the corresponding id
            for id in ids:
                if award_chat_points(db, id[0], points):  # Grant points
                    for user in get_all_users_with_user_id(db, id[0]):
                        name = user[1]
                        alerts_dict['gb_name'] = name
                        if not name:
                            name = 'Someone'
                            alerts_dict['gb_name'] = 'New Donation!'
                    current_app.logger.info(f'Granted user id {id[0]} {porps(points)} for their ${amount} donation.')
        if is_public:
            message = f'{name} got {porps(points)} for donating ${amount} on {donation_service}!'
            alerts_dict['gb_name'] = name
            current_app.logger.info(f'Public donation of ${amount} received from {name} via {donation_service}. Granted {porps(points)}.')
        else:
            message = f'We got an anonymous donation of ${amount}!'
            alerts_dict['gb_name'] = 'New Donation!'
            current_app.logger.info(f'Anonymous donation of ${amount} received via {donation_service}')
        if donation_service == 'GiveButter':  # If a GiveButter donation, update alerts.py, to trigger alert
            save_alerts(alerts_dict)
        send_chat(message)  # Send message to chat
        return True
    except Exception as aderror:
        current_app.logger.error(f'A general exception occurred in accept_donation: {aderror}')


def accept_kofi_sub(sub_info, sub_points):
    try:
        db = get_db()
        donation_service = "Ko-fi"
        is_public = sub_info[0]
        name = sub_info[1]
        email = sub_info[2]
        amount = sub_info[3]
        amount = int(float(amount))  # Convert from str to int
        message = sub_info[4]
        first_sub = sub_info[5]
        tier_name = sub_info[6]
        points = sub_points
        ids = get_id_by_email(db, email)
        if not ids:  # If no id found with that email address
            if add_email_to_points(db, email, points):  # Create empty account with email and points
                name = 'Someone'
                current_app.logger.info(f'No user with email \"{email}\" found in database, created empty Owncast account.')
        else:  # Grant points to the corresponding id
            for id in ids:
                if award_chat_points(db, id[0], points):  # Grant points
                    for user in get_all_users_with_user_id(db, id[0]):
                        name = user[1]  # Assign name from points table
                    current_app.logger.info(f'Awarded user id {id[0]} {porps(points)} for their subscription.')                
        if is_public:
            if not name:  # If no name in points table
                name = 'Someone'
            if first_sub:  # Kofi-only field
                message = f'{name} got {porps(points)} for their one month membership on {donation_service}!'
                current_app.logger.info(f'Public subscription received from {name}')
            else:
                message = f'{name} got {porps(points)} for renewing their membership on {donation_service}!'
                current_app.logger.info(f'Anonymous {donation_service} subcription renewal received.')
            send_chat(message)  # Send message publicly if a public membership
        else:
            if not ids:
                current_app.logger.info(f'No Owncast account to associate {donation_service} subscription with.')
                # return True
            if not name:  # If no name in points table
                name = sub_info[1]  # Assign name from Kofi response
            if first_sub:
                message = f'Thanks so much for your subscribing to my {donation_service}! You\'ve been awarded {porps(points)}!'
                current_app.logger.info(f'Anonymous {donation_service} subscription received.')
            else:
                message = f'Thanks so much for renewing your membership to my {donation_service}! You\'ve been awarded {porps(points)}!'
                current_app.logger.info(f'Anonymous {donation_service} subscription renewal received.')
            send_private_chat(id[0], message)
        return True
    except Exception as aderror:
        current_app.logger.error(f'A general exception occurred in accept_kofi_sub: {aderror}')


def save_kofi_settings(ksettings_info):  # Write settings to kofi.py
    settings_file = os.path.join(current_app.instance_path, 'kofi.py')
    try:
        with open(settings_file, 'w') as f:
            f.write(f'KOFI_SETTINGS = {ksettings_info}')
        f.close
        current_app.config.from_pyfile('kofi.py', silent=True)  # Reread kofi.py into the app
    except Exception as sks_error:
        current_app.logger.error(f'Couldn\'t save kofi.py: {sks_error}')
        return False

    return True


def save_gb_settings(gbsettings_info):  # Write settings to givebutter.py
    settings_file = os.path.join(current_app.instance_path, 'givebutter.py')
    try:
        with open(settings_file, 'w') as f:
            f.write(f'GB_SETTINGS = {gbsettings_info}')
        f.close
        current_app.config.from_pyfile('givebutter.py', silent=True)  # Reread givebutter.py into the app
    except Exception as sgbs_error:
        current_app.logger.error(f'Couldn\'t save givebutter.py: {sgbs_error}')
        return False

    return True
