#include "tools/arg_parse.h"

static error_t parse_opt(int key, char *arg, struct argp_state *state);

static char doc[] = "Optical Character Recognition (OCR)";
static char args_doc[] = "";
static struct argp_option options[] = {
    { "train", 't', 0, 0, "Train new model weight (default: off)", 0 },
    { "input-file", 'i', "FILE", 0, "File to recognise character from, can't be use in training mode (default: none)", 0 },
    { "save-weight", 's', "FILE", 0, "Save weight to FILE, must only be use in training mode (default: none)", 0 },
    { "load-weight", 'l', "FILE", 0, "Load weight from FILE (default: misc/nnweight/nnweight.txt)", 0 },
    { 0 } 
};

static struct argp argp = { options, parse_opt, args_doc, doc, 0, 0, 0 };

static error_t parse_opt(int key, char *arg, struct argp_state *state) {
    struct arguments *arguments = state->input;
    switch (key) {
    case 't': arguments->mode               = TRAIN; break;
    case 'i': arguments->input_file_path    = arg;   break;
    case 's': arguments->weight_output_path = arg;   break;
    case 'l': arguments->weight_input_path  = arg;   break;
    case ARGP_KEY_END:
        // Validate incompatible options
        if (*(arguments->input_file_path) == '\0' && (arguments->mode == RECOGNITION)) {
            fprintf(stderr, "Error: No input file given (use --input-file).\n");
            argp_usage(state);
        } else if (*(arguments->input_file_path) != '\0' && !(arguments->mode == RECOGNITION)) {
            fprintf(stderr, "Error: --train and --input-file cannot be used together.\n");
            argp_usage(state);
        } else if (*(arguments->weight_output_path) != '\0' && !(arguments->mode == TRAIN)) {
            fprintf(stderr, "Error: --save-weight in recognition mode (use --train).\n");
            argp_usage(state);
        }
        break;
    case ARGP_KEY_ARG: return 0;
    default: return ARGP_ERR_UNKNOWN;
    }   
    return 0;
}

void arg_parse(int argc, char *argv[], struct arguments *arguments) {
    argp_parse(&argp, argc, argv, 0, 0, arguments);
}
