/* main.c */

#include "computorv1.h"

/**
 * GLOBALS
 */

bool flag_debug_mode;
bool flag_loop_mode;
char *input_g_err;
s_token *tokens_g_err;
s_term *terms_g_err;
double *polynom_g_err;
int polynom_len_g_err;
s_solution *solution_g_err;

/**
 * PROGRAM
 */

// trim spaces and quotes and newlines
static void clean_copy_input(char *input, char *line)
{
    size_t i;
    size_t j;
    size_t len;
    size_t len_trim_end;
    size_t len_trim_start;

    len = ft_strlen(line);

    // get len minus : ' | " | \n | <space>
    i = len;
    while (i > 0)
    {
        if (ft_strchr("\"\'\n", line[i]))
            i--;
        if (ft_isspace(line[i]))
            i--;
        break;
    }
    len_trim_end = i;

    // get len of leading chars : ' | " | <space> | \n
    i = 0;
    while (i < len_trim_end)
    {
        if (ft_strchr("\"\'\n", line[i]))
            i++;
        if (ft_isspace(line[i]))
            i++;
        break;
    }
    len_trim_start = i;

    // copy into input
    i = len_trim_start;
    j = 0;
    while (i <= len_trim_end)
    {
        input[j] = line[i];
        j++;
        i++;
    }
    input[j] = '\0';
}

static void launch_stdin()
{
    char *line;
    size_t len;

    line = NULL;
    len = 0;

    // get input
    getline(&line, &len, stdin);

    // prepare input
    char input[len];
    clean_copy_input(input, line);

    // launch input
    launch_computorv1(input);

    // FREE LINE !
    free(line);
}

static void launch_stdin_loop()
{
    while (1)
    {
        // for the moment it does not work since errors exit
        launch_stdin();
    }
}

int main(int ac, char **av)
{
    int i;
    char *input;
    e_program_mode program_mode;

    // init flags
    flag_debug_mode = false;
    flag_loop_mode = false;

    // check arguments
    program_mode = MODE_ARGV;
    if (ac == 1)
    {
        program_mode = MODE_STDIN;
    }
    else if (ac > 1)
    {
        // get flags
        input = NULL;
        i = 1;
        while (i < ac)
        {
            if ((ft_strcmp(av[i], "-d") == 0))
            {
                flag_debug_mode = true;
            }
            else if ((ft_strcmp(av[i], "-l") == 0))
            {
                flag_loop_mode = true;
                program_mode = MODE_LOOP;
            }
            else if (ft_strlen(av[i]) == 2 && av[i][0] == '-')
            {
                stop_errors("unknwon flag '%s'", av[i]);
            }
            else
            {
                input = av[i];
            }
            i++;
        }
        // if input was not set, it means interactiv mode
        if (input == NULL)
        {
            program_mode = MODE_STDIN;
        }
    }

    // launch calculator
    if (program_mode == MODE_ARGV)
    {
        launch_computorv1(input);
    }
    else if (program_mode == MODE_STDIN)
    {
        launch_stdin();
    }
    else if (program_mode == MODE_LOOP)
    {
        launch_stdin_loop();
    }

    return (0);
}
