#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

%modern

%requires linenoise
%requires qore >= 2.0
%requires DebugCmdLine
%requires DebugLinenoiseCmdLine
%requires DebugProgramControl
%requires Util
%requires Logger

%allow-debugger
%no-debugging

%exec-class DebugWrapper

class DebugCommandLineLocal inherits DebugLinenoiseCommandLine {
    public {
        DebugProgramControlLocal dpc;
        ResponseSync sync();
    }
    constructor(DebugProgramControlLocal n_dpc): DebugLinenoiseCommandLine() {
        dpc = n_dpc;
        dpc.dcl = self;
    }
    public *hash<auto> doCommandImpl(hash<auto> data) {
        if (exists data.tid) {
            sync.prepare();
        }
        *hash<auto> ret = dpc.processCommand(DebugProgramControlLocal::CX, data);
        if (ret.type == DebugResponseType::Thread) {
            return sync.waitForResponse(200ms);
        } else {
            return ret;
        }
    }
}

class DebugProgramControlLocal inherits DebugProgramControl {
    public {
        DebugCommandLineLocal dcl;
    }
    const CX = ('id': 1);
    constructor () : DebugProgramControl(QORE_ARGV[0]) {
        registerConnection(CX);
    }
    destructor() {
        try {
            unregisterConnection(CX);
        } catch () {
            # suppress exceptions during program shutdown (PROGRAM-ERROR)
        }
    }
    public nothing sendDataImpl(hash<auto> cx, any data) {    # TODO: nothing needed. why? I cannot reproduce in simple case to report issue
        debug("sendDataImpl: %y: %y", cx, data);
        if (!dcl.sync.deliver(data)) {
            dcl.printData(data);
        }
    }
    public nothing broadcastDataImpl(any data) {
        debug("broadcastDataImpl: %y", data);
        dcl.printData(data);
    }
}

class DebugWrapper {
    private {
        hash<auto> opts = (
            'help': 'h,help',
            'verbose': 'v,verbose:+',
            'run': 'r,run',
            "parse_option": "p,set-parse-option=s@",
            #"charset": "c,charset=s",
            "define": "D,define=s@",
            "time_zone": "z,time-zone=s",
            #"exec_class": "x,exec-class:s",
            "history": "y,history=s",
            "session": "s,session=s",
            "color": "color",
            "no_color": "no-color",
        );
        DebugCommandLineLocal dcl;
        Logger logger;
    }

    constructor() {
        WrapperGetOpt g(opts);
        # first we need split debug args and program args, 'qore-dbg debug-args program-name program-args'
        # it is not trivial, e.g.
        #    qore-dbg -v -l xxx xxx         #the second xxx is program name
        #    qore-dbg -v -h xxx xxx         #the first xxx is program name
        #    qore-dbg -v --listen=xxx xxx   #the second xxx is program name
        #    qore-dbg -v --listen xxx xxx   #the second xxx is program name
        # GetOpt does not support such a parse function
        #
        list<auto> dargs;
        hash<auto> opt;
        *string fileName;
        g.split(cast<list<string>>(ARGV), \dargs, \fileName, \ARGV);

        try {
            opt = g.parse2(\dargs);
        } catch (hash<ExceptionInfo> ex) {
            stderr.printf("%s: %s\n", ex.err, ex.desc);
            help(-1);
        }

        if (opt.help) {
            help();
        }
        logger = new Logger();
        logger.addAppender(new LoggerAppenderStdErr("stderr", new LoggerLayoutPattern("%d{YYYY-MM-DD HH:mm:SS.xx} T%t [%p]: %m%n")));
        if (opt.verbose > 1) {
            logger.setLevel("DEBUG");
        } else if (opt.verbose) {
            logger.setLevel("INFO");
        } else {
            logger.setLevel("ERROR");
        }
        DebugProgramControlLocal dpcl();
        dcl = new DebugCommandLineLocal(dpcl);
        dcl.setLogger(logger);
        dcl.dpc.setLogger(logger);
        # signal handler for graceful shutdown
        code sig_handler = sub (int sig) {
            dpcl.shutdown();
        };
        set_signal_handler(SIGINT, sig_handler);
        set_signal_handler(SIGTERM, sig_handler);
        try {
            if (fileName == "--") {
                fileName = "/dev/stdin";
            }
            if (exists fileName) {
                Program pgm = dcl.dpc.createProgram(fileName, opt, ARGV);
                logger.info("run program");
                background pgm.run();
            }
            dcl.init(opt);
            dcl.runCmdLine();

            # explicit cleanup before program exit to avoid PROGRAM-ERROR
            # in destructors when module programs are destroyed first
            dpcl.shutdown();
        } catch (hash<ExceptionInfo> ex) {
            stderr.print(get_exception_string(ex) + "\n");
            exit(-1);
        }
        # remove signal handlers before exit so their closures release
        # references to dpcl; otherwise dpcl is destroyed during program
        # shutdown when module programs may already be deleted
        remove_signal_handler(SIGINT);
        remove_signal_handler(SIGTERM);
    }

    private help(int exCode=1) {
        printf("usage: %s [options] <program> [<program params> ...]\n"
            "  where <program> is the program to debug, use \"--\" to get code from stdin\n"
            "  -v                           verbose (use -v -v for debug output)\n"
            "  -h                           help\n"
            "  -D, --define=arg             sets the value of a parse define\n"
            "  -p, --set-parse-option=arg   set parse option (ex: -pno-database)\n"
            "  -z, --time-zone=arg          sets the time zone from the argument; can be\n"
            "                               a region name (ex: 'Europe/Prague') or a\n"
            "                               UTC offset (ex: '+01:00')\n"
            "  -y, --history=file           load command line history from file, default: %s in home directory\n"
            "                               When \".\" name is provided then history is not loaded/saved\n"
            "  -s, --session=file           load session from file\n"
            "  --color                      force color output\n"
            "  --no-color                   disable color output\n"
            "\n"
            "Keyboard shortcuts:\n"
            "  Ctrl+D                       quit debugger\n"
            "  Ctrl+G                       show current program/thread context\n"
            "  TAB                          command completion (cycles through matches)\n"
            "\n"
            "Example:\n"
            "  %s -v myfile.q -my -program params\n"
            "\n"
            ,
            get_script_name(),
            DebugLinenoiseCommandLine::defaultHistoryFileName,
            get_script_name(),
        );
        exit(exCode);
    }


    public dummy() {
    }
}
