#include <stdio.h>
#include <unistd.h>

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>

#include <paint.h>
#include <validate.h>
#include <gtk_stuff.h>

GtkApplication* app;

/**
 * Activates the GUI application.
 * Checks to see if the key is valid, if it is we start the paint app
 * otherwise it shows the license key popup.
 */
void app_start()
{
    GtkWidget* app_window = gtk_application_window_new(app);
    
    /* If we already have a key file try and load it from disk */
    FILE *f = fopen(KEYSTORE_FILE, "r");
    if (f != NULL)
    {
        char* loaded_key = malloc((KEYLENGTH + 1) * sizeof(char));

        /* Read in the key */
        fread(loaded_key, sizeof(char), KEYLENGTH, f);
        /* Check for validity */
        int valid_key = check_is_key_valid(loaded_key);
        fclose(f);
        free(loaded_key);
        
        if (valid_key)
        {
            /* The key was valid, start the program */
            build_paint();
            return;
        }

        /* If we end up here the key was not valid */
    }

    build_license_key_popup();
}

int main(int argc, char** argv)
{
    int status;
    
    app = gtk_application_new("org.gtk.superhightechpaint", G_APPLICATION_FLAGS_NONE);

    g_signal_connect(app, "activate", G_CALLBACK(app_start), NULL);
    status = g_application_run(G_APPLICATION(app), argc, argv);

    g_object_unref(app);
    return status;
}