import os
import logging
from flask import Flask, g
from flask_cors import CORS
from ownchatbot.db import get_db
from ownchatbot.owncast_com import live_now, award_points, send_system_chat
from apscheduler.schedulers.background import BackgroundScheduler

current_index = 0


def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    CORS(app)  # Enable CORS for all routes

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    app.config.from_mapping(
        DATABASE=os.path.join(app.instance_path, 'ownchatbot.sqlite')
    )
    app.config.from_object('ownchatbot.defaults.config')  # Read from config files
    app.config.from_pyfile('config.py', silent=True)
    app.config.from_object('ownchatbot.defaults.rewards')
    app.config.from_pyfile('rewards.py', silent=True)
    app.config.from_object('ownchatbot.defaults.categories')
    app.config.from_pyfile('categories.py', silent=True)
    app.config.from_object('ownchatbot.defaults.kofi')
    app.config.from_pyfile('kofi.py', silent=True)
    app.config.from_object('ownchatbot.defaults.announce')
    app.config.from_pyfile('announce.py', silent=True)
    app.config.from_object('ownchatbot.defaults.todo')
    app.config.from_pyfile('todo.py', silent=True)
    app.config.from_object('ownchatbot.defaults.alerts')
    app.config.from_pyfile('alerts.py', silent=True)
    app.config.from_object('ownchatbot.defaults.givebutter')
    app.config.from_pyfile('givebutter.py', silent=True)
    app.config['ASSETS_FOLDER'] = os.path.join(app.instance_path, 'assets')

    gunicorn_logger = logging.getLogger('gunicorn.error')
    app.logger.handlers = gunicorn_logger.handlers
    app.logger.setLevel(gunicorn_logger.level)

    from . import webhooks  # Set up blueprints
    from . import web_panels
    app.register_blueprint(webhooks.ocb)
    app.register_blueprint(web_panels.ocb)

    from . import db  # Set up cli commands
    db.init_app(app)

    def announce():
        global current_index
        app.config.from_pyfile('announce.py', silent=True)
        announcements = app.config['ANNOUNCEMENTS']
        if current_index >= len(announcements):  # If reached the last announement, reset index
            current_index = 0
        try:
            message = announcements[current_index]
            send_system_chat(message)
            current_index = (current_index + 1) % len(announcements)
        except Exception as a_error:
            app.logger.error(f'Couldn\'t make announcement: {a_error}')
                
    def award_job():
        with app.app_context():
            if live_now():  # If stream is live
                award_points(get_db())
                
    def announce_job():
        with app.app_context():
            if app.config['ANNOUNCE_ENABLE']:  # If announcements are enabled
                if live_now():  # If stream is live
                    announce()
                else:
                    app.logger.debug(f'Not live, so not sending announcement.')
            else:
                app.logger.debug(f'Announcements not enabled.')

    jorel_master_of_scheduling = BackgroundScheduler()
    points_seconds = app.config['POINTS_INTERVAL'] * 60
    announce_seconds = app.config['ANNOUNCE_INTERVAL'] * 60
    jorel_master_of_scheduling.add_job(award_job, 'interval', seconds=points_seconds)
    jorel_master_of_scheduling.add_job(announce_job, 'interval', seconds=announce_seconds)
    jorel_master_of_scheduling.start()

    return app


if __name__ == '__main__':
    create_app()
