#!/usr/bin/python3.5

import os
import sys
import signal
import unittest
import datetime

from modules.scheduling.scheduler import AuraScheduler
from modules.communication.liquidsoap.communicator import LiquidSoapCommunicator
from modules.communication.redis.adapter import ServerRedisAdapter
from modules.web.routes import Routes
from modules.monitoring.diskspace_watcher import DiskSpaceWatcher
from libraries.base.logger import AuraLogger

from testing.test import TestConfig, TestLogger
from flask import request, render_template, Flask, Response

app = Flask(__name__)
config = None

class Aura(AuraLogger):
    server = None
    messenger = None
    controller = None

    # ------------------------------------------------------------------------------------------ #
    def __init__(self):
        super(Aura, self).__init__()

    def test_yourself(self):
        self.run_test(TestConfig)
        self.run_test(TestLogger)

    def run_test(self, testingClass):
        runner = unittest.TextTestRunner()
        result = runner.run(unittest.makeSuite(testingClass))

    def startup(self):

        server = object

        #        self.controller = AuraController(self.config)
        # create scheduler and ls_communicator
        self.liquidsoapcommunicator = LiquidSoapCommunicator(self.config)
        self.scheduler = AuraScheduler(self.config)

        # give both a reference of each other
        self.liquidsoapcommunicator.scheduler = self.scheduler
        self.scheduler.liquidsoapcommunicator = self.liquidsoapcommunicator

        # create the redis adapter
        self.messenger = ServerRedisAdapter(self.config)
        self.messenger.scheduler = self.scheduler
        self.messenger.liquidsoapcommunicator = self.liquidsoapcommunicator

#        self.diskspace_watcher = DiskSpaceWatcher(self.config, self.logger, self.liquidsoapcommunicator)
#        self.diskspace_watcher.start()

        

        def receive_signal(signum, stack):
            print("received signal")
            server.reload()

        signal.signal(signal.SIGUSR1, receive_signal)

        # and finally wait for redis message
        self.join_comm()

        global config
        config = self.config
        # start the web service
        self.start_web_service()



    def join_comm(self):
        # start listener thread
        self.messenger.start()

    def start_web_service(self):
        try:
            i = 0
            #app.run()
            #self.logger.info("Listening on Port 5000 for API or Webcalls")
            #Routes(None, None, None) # self.scheduler, self.liquidsoapcommunicator, self.messenger)
        except OSError as e:
            self.messenger.halt()
            self.logger.critical("AuraEngine already running? Exception: " + e.strerror + ". Exiting...")
            os._exit(0)


@staticmethod
@app.route('/')
@app.route('/index')
@app.route('/index.php')
@app.route('/index.html')
def index():
    return render_template(config.get(str("install_dir")) + "/modules/web/templates/index.html")

@staticmethod
@app.route("/api/v1/upcoming/", methods=["GET"])
def api_clock():
    #aura.
    #servertime = datetime.datetime.now()
    # get upcoming tracks
    #upcoming = ScheduleEntry.select_upcoming()
    # convert to json string
    #upcoming_as_json = json.dumps([tracks._asdict() for tracks in upcoming], default=alchemyencoder)
    # add servertime and return it
    return "Nothing" # upcoming_as_json.replace('[{', '[{"servertime":'+str(servertime)+"},{", 1)


aura = Aura()
aura.startup()
app.run()

# # ## ## ## ## ## # #
# # ENTRY FUNCTION # #
# # ## ## ## ## ## # #
#def main():
#    aura = Aura()


#    if len(sys.argv) >= 2 and sys.argv[1] == "--na-gspiast-di-?":
#        aura.test_yourself()
#    else:
#        aura.startup()

#    app.run()


# # ## ## ## ## ## ## # #
# # End ENTRY FUNCTION # #
# # ## ## ## ## ## ## # #


#if __name__ == "__main__":
#    main()