#include "main.h"
#include "download.h"
#include "inspect.h"
#include "confirm.h"
#include "cleanup.h"
#include "resolve.h"
#include "search.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <json-c/json_object.h>

/**
 * Return a pointer to a Package struct located in heap memory.
 * Initialise said struct with `name`, and set every pointer in the
 * `depends_list` array to NULL
 */
struct Package *construct_package(char *name)
{
    struct Package *package = malloc(sizeof(struct Package));
    package->name = name;
    package->installed = 0;
    for (int i = 0; i < MAX_DEPS; i++) {
        package->depends_list[i] = NULL;
    }
    package->aur = 0;

    return package;
}

int main(int argc, char **argv)
{
    if (argc == 1)
        return 1;

    if (strcmp(argv[1], "install") == 0) {
        for (int i = 2; i < argc; i++) {
            struct Package *package = construct_package(argv[i]);
            struct Package **list_of_packages = malloc(sizeof(struct Package *));

            int *number_of_packages = malloc(sizeof(int));
            *number_of_packages = 0;

            printf("==> Creating dependency graph of package...\n");
            create_dependency_graph(package, &list_of_packages, number_of_packages);
            print_packages_in_dependency_chain(list_of_packages, *number_of_packages);
            if (!confirm("==> Proceed?")) {
                return 1;
            }

            download_package(package);
            if (confirm("==> Inspect PKGBUILD?")) {
                inspect_pkgbuild(package);
            }
            if (confirm("==> Build package?")) {
                resolve_dependency_graph(package);
            }
            if (confirm("==> Remove source directory?")) {
                cleanup(package);
            }

            free(package);
            free(list_of_packages);
            free(number_of_packages);
        }
    } else if (strcmp(argv[1], "search") == 0) {
        for (int i = 2; i < argc; i++) {
            json_object *results = search_for_packages(argv[i]);
            interpret_search_results(results);
            json_object_put(results);
        }
    } else if (strcmp(argv[1], "info") == 0) {
        for (int i = 2; i < argc; i++) {
            json_object *results = info_about_package(argv[i]);
            interpret_info_results(results);
            json_object_put(results);
        }
    } else {
        printf("%s%serror%s: expected one of 'install`, 'search', 'info'; got '%s'\n", BOLD, BRIGHT_RED, CLR, argv[1]);
        return 1;
    }

    return 0;
}
