#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Stashr - Server Start
"""

"""
MIT License

Copyright (c) 2020 Andrew Vanderbye

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

"""-------------------------------------------------------------------------------------------
-- IMPORTS
-------------------------------------------------------------------------------------------"""

""" --- PYTHON IMPORTS --- """
import os, signal
from socket import error as SocketError

""" --- STASHR DEPENDENCY IMPORTS --- """
""" --- STASHR CORE IMPORTS --- """
from stashr.stashr import app
from stashr import log
from stashr import database, routes
from stashr.config import stashrconfig

""" --- GEVENT IMPORT --- """
from gevent.pywsgi import WSGIServer
from gevent.pool import Pool

""" --- CREATE LOGGER --- """
logger = log.stashr_logger(__name__)

"""-------------------------------------------------------------------------------------------
-- SERVER
-------------------------------------------------------------------------------------------"""


class Server:

    wsgiserver = None
    restart = False

    def __init__(self):
        try:
            signal.signal(signal.SIGHUP, self.restart_server)
        except:
            signal.signal(signal.SIGINT, self.restart_server)
            pass

    def define_wsgi(self):
        try:
            ssl_args = dict()
            if os.name == 'nt':
                app.logger.debug('NT')
                app.logger.debug('PORT: {0}'.format(stashrconfig['APP']['server_port']))
                self.wsgiserver = WSGIServer(('0.0.0.0', int(stashrconfig['APP']['server_port'])), app, spawn=Pool(), **ssl_args)
            else:
                app.logger.debug('NOT NT')
                app.logger.debug('PORT: {0}'.format(stashrconfig['APP']['server_port']))
                self.wsgiserver = WSGIServer(('', int(stashrconfig['APP']['server_port'])), app, spawn=Pool(), **ssl_args)
        except SocketError:
            app.logger.debug('PORT: {0}'.format(stashrconfig['APP']['server_port']))
            self.wsgiserver = WSGIServer(('0.0.0.0', int(stashrconfig['APP']['server_port'])), app, spawn=Pool(), **ssl_args)
        except Exception:
            app.logger.debug('Unknown Error while starting gevent')

    def start_server(self):
        app.logger.debug('STARTING SERVER')
        self.define_wsgi()
        self.wsgiserver.serve_forever()

    def stop_server(self):
        app.logger.debug('STOPPING SERVER')
        self.wsgiserver.stop()

    def restart_server(self, ignored_signum, ignored_frame):
        app.logger.debug('Restarting Server')
        print('restatr')
        self.wsgiserver.close()
        # self.define_wsgi()
        self.wsgiserver.start()


server = Server()
