# -*- coding: utf-8 -*-
from threading import Thread
import argparse
import logging
import os
import signal
import sys
import time

from pymrf4.mrf_context import MRFContext


if os.name == 'nt':  # Windows
    import msvcrt
else:  # Unix-like (Linux/macOS)
    import tty
    import termios

def get_single_char():
    if os.name == 'nt':  # Windows
        char = msvcrt.getch().decode('utf-8')
    else:  # Unix-like (Linux/macOS)
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            char = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return char



parser = argparse.ArgumentParser(
    description='pymrf4'
)
parser.add_argument('--host',
                type=str,
                default="0.0.0.0",
                help='Listen host.')
parser.add_argument('--port',
                type=int,
                default=9050,
                help='Listen port.')
parser.add_argument('--web-ui-port',
                type=int,
                default=5090,
                help='Web UI listen port.')
parser.add_argument('-d', '--master-disable',
                type=bool,
                default=False,
                help='Master switch that controls if hook should work.')


def config_logger():
    root = logging.getLogger()

    root.setLevel(logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    root.addHandler(ch)

    # 目前存在当前目录下
    timestamp_s = time.strftime("%Y%m%d-%H%M%S")
    fh = logging.FileHandler(os.path.join(os.getcwd(), 'logs', f'{timestamp_s}.log'))
    # fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)
    root.addHandler(fh)

    root.handlers = [ch, fh]

def cli():
    config_logger()
    # parse args
    args = parser.parse_args(args=sys.argv[1:])
    logging.getLogger().debug(args)

    mrf = MRFContext()
    mrf.spin_up_daemons(host=args.host, port=args.port, web_ui_port=args.web_ui_port)

    def key_monitor():
        while True:
            char = get_single_char().strip().lower()
            # for line in sys.stdin:
            if 'x' == char:
                mrf.shutdown_daemons()
                logging.info("MRF daemons has been shut down.")
                mrf.stop_timers()
                logging.info("Timers are stopped.")
            
            elif 'r' == char:
                logging.info("Reloading config...")
                mrf.read_config()

    Thread(name="Key Monitor", target=key_monitor).start()

    # Ctrl-C handling
    # def sig_int_handler(signum, frame):
    #     mrf.shutdown_daemons()
    #     mrf.stop_timers()
        
    #     # ptff.stop_timers()
    #     logging.info("Exiting, saving all context objects.")
    #     fcm.save_all()
        
    # signal.signal(signal.SIGTERM, sig_int_handler)
    # signal.signal(signal.SIGINT, sig_int_handler)
    # signal.signal(signal.SIGBREAK, sig_int_handler)

    


if __name__ == '__main__':
    # config logger
    config_logger()
    
    cli()
    