#include "ui.h"
#include <stdio.h>
#include <stdarg.h>
#include <jansson.h>
size_t bookmark_list_index = 0;
size_t bookmark_count_for_user = 0;

verse_bookmark_t *bookmarks = NULL;

app_data_t data;

void bookmark_list()
{
    bookmark_count_for_user = 0;
    size_t i;
    for (i = 0; i < data.noBookmarkedVerses; i++)
    {
        if (data.bookmarkedVerses[i].user == data.index)
        {
            bookmark_count_for_user++;
        }
    }
    if (bookmarks != NULL)
    {
        free(bookmarks);
        bookmarks = NULL;
    }
    bookmarks = (verse_bookmark_t *)malloc(sizeof(verse_bookmark_t) * bookmark_count_for_user);
    size_t j = 0;
    for (i = 0; i < data.noBookmarkedVerses; i++)
    {
        if (data.bookmarkedVerses[i].user == data.index)
        {
            bookmarks[j] = data.bookmarkedVerses[i];
            j++;
        }
    }
}
const char *json_file = "biible_bookmarks.json";

int bookmark_indexof()
{
    if (data.noBookmarkedVerses <= 0)
        return -1;
    int i;
    for (i = 0; i < (int)data.noBookmarkedVerses; i++)
    {
        verse_bookmark_t *bookmark = &data.bookmarkedVerses[i];
        if (data.curBible == bookmark->bible && data.index == bookmark->user && data.curBook == bookmark->book && data.curChapter == bookmark->chapter && data.curVerse == bookmark->verse)
        {
            return i;
        }
    }
    return -1;
}
void bookmark_remove(size_t index)
{

    if (index == -1)
        return;
    data.noBookmarkedVerses--;
    for (; index < data.noBookmarkedVerses; index++)
    {
        data.bookmarkedVerses[index] = data.bookmarkedVerses[index + 1];
    }
    FILE *f = fopen(json_file, "w");
    if (f)
    {
        json_t *array = json_array();
        size_t i;
        for (i = 0; i < data.noBookmarkedVerses; i++)
        {
            json_t *val = json_object();
            verse_bookmark_t *bookmark = &data.bookmarkedVerses[i];
            json_object_set_new(val, "user", json_integer(bookmark->user));
            json_object_set_new(val, "bible", json_integer(bookmark->bible));
            json_object_set_new(val, "book", json_integer(bookmark->book));
            json_object_set_new(val, "chapter", json_integer(bookmark->chapter));
            json_object_set_new(val, "verse", json_integer(bookmark->verse));
            json_array_append_new(array, val);
        }
        json_dumpf(array, f, 0);
        json_decrefp(&array);
    }
}
void bookmark_add()
{

    if (data.noBookmarkedVerses + 1 > data.bookmarkedVersesCap)
    {
        data.bookmarkedVersesCap += 16;
        data.bookmarkedVerses = (verse_bookmark_t *)realloc(data.bookmarkedVerses, sizeof(verse_bookmark_t) * data.bookmarkedVersesCap);
    }
    verse_bookmark_t *bookmark = &data.bookmarkedVerses[data.noBookmarkedVerses++];
    bookmark->bible = data.curBible;
    bookmark->book = data.curBook;
    bookmark->chapter = data.curChapter;
    bookmark->verse = data.curVerse;
    bookmark->user = data.index;
    FILE *f = fopen(json_file, "w");
    if (f)
    {
        json_t *array = json_array();
        size_t i;
        for (i = 0; i < data.noBookmarkedVerses; i++)
        {
            json_t *val = json_object();
            verse_bookmark_t *bookmark = &data.bookmarkedVerses[i];
            json_object_set_new(val, "user", json_integer(bookmark->user));
            json_object_set_new(val, "bible", json_integer(bookmark->bible));
            json_object_set_new(val, "book", json_integer(bookmark->book));
            json_object_set_new(val, "chapter", json_integer(bookmark->chapter));
            json_object_set_new(val, "verse", json_integer(bookmark->verse));
            json_array_append_new(array, val);
        }
        json_dumpf(array, f, 0);
        json_decrefp(&array);
    }
}

void UiInit()
{

    data.index = 0;
    data.page = PAGE_BIBLE_LIST;
    data.curBible = 0;
    data.curBook = 0;
    data.curChapter = 0;
    data.curVerse = 0;

    FILE *f = fopen(json_file, "r");
    if (f)
    {
        json_t *json = json_loadf(f, 0, NULL);

        data.noBookmarkedVerses = json_array_size(json);
        data.bookmarkedVersesCap = data.noBookmarkedVerses + 16;
        data.bookmarkedVerses = (verse_bookmark_t *)malloc(sizeof(verse_bookmark_t) * data.bookmarkedVersesCap);
        size_t i;
        for (i = 0; i < data.noBookmarkedVerses; i++)
        {
            verse_bookmark_t *bookmark = &data.bookmarkedVerses[i];
            json_t *bm = json_array_get(json, i);
            bookmark->user = json_integer_value(json_object_get(bm, "user"));
            bookmark->bible = json_integer_value(json_object_get(bm, "bible"));
            bookmark->book = json_integer_value(json_object_get(bm, "book"));
            bookmark->chapter = json_integer_value(json_object_get(bm, "chapter"));
            bookmark->verse = json_integer_value(json_object_get(bm, "verse"));
        }

        json_decrefp(&json);
    }
    else
    {
        data.bookmarkedVersesCap = 0;
        data.noBookmarkedVerses = 0;
        data.bookmarkedVerses = (verse_bookmark_t *)malloc(sizeof(verse_bookmark_t));
    }

    LoadBibles(&data);

    UiRender();
}
void printSomething(const char *format, BOOL isOver, ...)
{
    printf(isOver ? "\033[47m\033[30m" : "\033[37m\033[40m");
    va_list args;
    va_start(args, isOver);
    vprintf(format, args);
    va_end(args);
}
void UiRender()
{
    printf("\033[37m\033[40m");
    puts("\033[2J");

    if (data.page == PAGE_BIBLE_LIST)
    {
        printf("^ Bible/Bookmarks V\n");
        printf("A: Select Bible/Bookmarks\n");
        printf("START or HOME (any screen): Quit\n");
        printSomething("Bookmarks\n", data.index % 5 == 0);
        size_t i;
        for (i = 0; i < 4; i++)
        {
            printSomething("%s\n", data.index % 5 == (i + 1), data.bibles[i].name);
        }
    }
    else if (data.page == PAGE_BOOK_LIST)
    {
        
        bible_t *curBible = &(data.bibles[data.curBible]);
        size_t i = 0;
        size_t len = 20;
        if (curBible->noBooks < 20)
            len = curBible->noBooks;

        size_t offset = data.index % len;
        size_t line = (data.index - offset);
        // if((Items.Count-line) < len) len = Items.Count - line;
        if (curBible->noBooks - line < len)
            len = curBible->noBooks - line;
        printf("^ Book V\n");
        printf("A: Select Book\n");
        printf("B: Bible Select\n");
        for (i = line; i < line + len; i++)
        {
            book_t *hbook = &curBible->books[i];
            printSomething("%s\n", data.index == i, hbook->name);
        }
    }
    else if (data.page == PAGE_CHAPTER_LIST)
    {
        bible_t *bible = &data.bibles[data.curBible];
        book_t *book = &bible->books[data.curBook];
        printf("Book: %s\n^ Chapter %i/%i V\n", book->name, data.index + 1, book->noChapters);
    }
    else if (data.page == PAGE_CHAPTER_VIEW)
    {
          book_t *curBook = &(data.bibles[data.curBible].books[data.curBook]);
       
        printf("<- Chapter %i/%i ->\n", data.curChapter + 1, curBook->noChapters);
        printf("^ Verse %i/ V\n", data.curVerse + 1);
        printf("A: Bookmark menu\n");
        printf("B: Chapter select\n");
        chapter_t *curChapter = &(curBook->chapters[data.curChapter]);
        size_t i = 0;
        size_t len = 5;
        if (curChapter->noVerses < 5)
            len = curChapter->noVerses;

        size_t offset = data.index % len;
        size_t line = (data.index - offset);
        // if((Items.Count-line) < len) len = Items.Count - line;
        if (curChapter->noVerses - line < len)
            len = curChapter->noVerses - line;

        for (i = line; i < line + len; i++)
        {
            char *verse = curChapter->verses[i];
            printSomething("%s %i:%i %s\n", data.index == i, curBook->name, data.curChapter + 1, i + 1, verse);
        }
    }
    else if (data.page == PAGE_BOOKMARK_MENU)
    {
        printf("<- User %i ->\n", data.index);
        printf("^ Verse %i V\n", data.curVerse + 1);
        printf("A: %s\n", bookmark_indexof() > -1 ? "Unbookmark" : "Bookmark");
        printf("B: View Chapter\n");
        printf("\n");
        book_t *curBook = &(data.bibles[data.curBible].books[data.curBook]);
        chapter_t *curChapter = &(curBook->chapters[data.curChapter]);
        char *verse = curChapter->verses[data.curVerse];
        printf("%s %i:%i %s\n", curBook->name, data.curChapter + 1, data.curVerse + 1, verse);
    }
    else if (data.page == PAGE_BOOKMARK_VIEW)
    {
        
        size_t i = 0;
        size_t len = 5;
        if (bookmark_count_for_user < 5)
            len = bookmark_count_for_user;

        size_t offset = bookmark_list_index % len;
        size_t line = (bookmark_list_index - offset);
        // if((Items.Count-line) < len) len = Items.Count - line;
        if (bookmark_count_for_user - line < len)
            len = bookmark_count_for_user - line;

        printf("<- User %i ->\n", data.index);
        printf("^ Bookmark %i V\n", bookmark_list_index + 1);
        printf("A: Jump To Verse\n");
        printf("B: Bible Select\n");
        for (i = line; i < line + len; i++)
        {
            if (i < bookmark_count_for_user)
            {
                verse_bookmark_t *bm = &bookmarks[i];
                if (bm->bible >= 4 || bm->bible < 0)
                    continue;

                bible_t *bible = &data.bibles[bm->bible];

                if (bm->book >= bible->noBooks || bm->book < 0)
                    continue;

                book_t *book = &bible->books[bm->book];

                if (bm->chapter >= book->noChapters || bm->chapter < 0)
                    continue;

                chapter_t *chapter = &book->chapters[bm->chapter];

                if (bm->verse >= chapter->noVerses || bm->verse < 0)
                    continue;
                char *verse = chapter->verses[bm->verse];
                printSomething("%s %i:%i %s\n", bookmark_list_index == i, book->name, bm->chapter + 1, bm->verse + 1, verse);
            }
            /*
            char* verse = curChapter->verses[bookmarks[i]];
            printSomething("%s %i:%i %s\n",bookmark_list_index == i,curBook->name,data.curChapter+1,bookmarks[i].verse,verse);*/
        }
    }
    printf("\033[37m\033[40m");
}
BOOL UiUpdate(u32 pad)
{
    if (data.page == PAGE_BIBLE_LIST)
    {
        if (pad & PAD_BUTTON_DOWN)
        {
            data.index++;
            if (data.index > 4)
                data.index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_UP)
        {
            data.index--;
            if (data.index < 0)
                data.index = 4;
            return true;
        }
        if (pad & PAD_BUTTON_A)
        {
            if (data.index > 0 && data.page < 6)
            {

                data.curBible = data.index - 1;
                data.index = 0;
                data.page = PAGE_BOOK_LIST;
                return true;
            }
            else
            {
                bookmark_count_for_user = 0;

                data.index = 0;
                bookmark_list();
                data.page = PAGE_BOOKMARK_VIEW;
                return true;
            }
        }
    }
    else if (data.page == PAGE_BOOK_LIST)
    {
        if (pad & PAD_BUTTON_DOWN)
        {
            data.index++;
            if (data.index >= data.bibles[data.curBible].noBooks)
                data.index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_UP)
        {
            data.index--;
            if (data.index < 0)
                data.index = data.bibles[data.curBible].noBooks - 1;
            return true;
        }
        if (pad & PAD_BUTTON_A)
        {
            data.curBook = data.index;
            data.page = PAGE_CHAPTER_LIST;
            data.index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_B)
        {
            data.index = data.curBible + 1;
            data.page = PAGE_BIBLE_LIST;
            return true;
        }
    }
    else if (data.page == PAGE_CHAPTER_LIST)
    {

        if (pad & PAD_BUTTON_DOWN)
        {
            data.index++;
            if (data.index >= data.bibles[data.curBible].books[data.curBook].noChapters)
                data.index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_UP)
        {
            data.index--;
            if (data.index < 0)
                data.index = data.bibles[data.curBible].books[data.curBook].noChapters - 1;
            return true;
        }
        if (pad & PAD_BUTTON_A)
        {
            data.curChapter = data.index;
            data.page = PAGE_CHAPTER_VIEW;
            data.index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_B)
        {
            data.index = data.curBook;
            data.page = PAGE_BOOK_LIST;
            return true;
        }
    }
    else if (data.page == PAGE_CHAPTER_VIEW)
    {
        if (pad & PAD_BUTTON_RIGHT)
        {
            data.curChapter++;
            if (data.curChapter >= data.bibles[data.curBible].books[data.curBook].noChapters)
                data.curChapter = 0;
            return true;
        }
        if (pad & PAD_BUTTON_LEFT)
        {
            data.curChapter--;
            if (data.curChapter < 0)
                data.curChapter = data.bibles[data.curBible].books[data.curBook].noChapters - 1;
            return true;
        }
        if (pad & PAD_BUTTON_DOWN)
        {
            data.index++;
            if (data.index >= data.bibles[data.curBible].books[data.curBook].chapters[data.curChapter].noVerses)
                data.index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_UP)
        {
            data.index--;
            if (data.index < 0)
                data.index = data.bibles[data.curBible].books[data.curBook].chapters[data.curChapter].noVerses - 1;
            return true;
        }
        if (pad & PAD_BUTTON_A)
        {
            data.curVerse = data.index;
            data.index = 0;
            data.page = PAGE_BOOKMARK_MENU;
            return true;
        }
        if (pad & PAD_BUTTON_B)
        {
            data.index = data.curChapter;
            data.page = PAGE_CHAPTER_LIST;
            return true;
        }
    }
    else if (data.page == PAGE_BOOKMARK_MENU)
    {
        if (pad & PAD_BUTTON_DOWN)
        {
            data.curVerse++;
            if (data.curVerse >= data.bibles[data.curBible].books[data.curBook].chapters[data.curChapter].noVerses)
                data.curVerse = 0;
            return true;
        }
        if (pad & PAD_BUTTON_UP)
        {
            data.curVerse--;
            if (data.curVerse < 0)
                data.index = data.bibles[data.curBible].books[data.curBook].chapters[data.curChapter].noVerses - 1;
            return true;
        }
        if (pad & PAD_BUTTON_LEFT)
        {
            data.index--;
        }
        if (pad & PAD_BUTTON_RIGHT)
        {
            data.index++;
        }
        if (pad & PAD_BUTTON_A)
        {
            int index = bookmark_indexof();
            if (index > -1)
            {
                bookmark_remove(index);
            }
            else
            {
                bookmark_add();
            }
            data.index = data.curVerse;
            data.page = PAGE_CHAPTER_VIEW;
            return true;
        }
        if (pad & PAD_BUTTON_B)
        {
            data.index = data.curVerse;
            data.page = PAGE_CHAPTER_VIEW;
            return true;
        }
    }
    else if (data.page == PAGE_BOOKMARK_VIEW)
    {
        if (pad & PAD_BUTTON_LEFT)
        {
            data.index--;
            bookmark_list_index = 0;
            bookmark_count_for_user = 0;
            bookmark_list();
            return true;
        }
        if (pad & PAD_BUTTON_RIGHT)
        {
            data.index++;
            bookmark_list_index = 0;
            bookmark_count_for_user = 0;
            bookmark_list();
            return true;
        }
        if (pad & PAD_BUTTON_UP)
        {
            bookmark_list_index--;
            if (data.index < 0)
                bookmark_list_index = bookmark_count_for_user - 1;
            return true;
        }
        if (pad & PAD_BUTTON_DOWN)
        {
            bookmark_list_index++;
            if (data.index >= bookmark_count_for_user)
                bookmark_list_index = 0;
            return true;
        }
        if (pad & PAD_BUTTON_A)
        {
            // check to make sure
            if (bookmark_list_index < bookmark_count_for_user)
            {
                verse_bookmark_t *bm = &bookmarks[bookmark_list_index];
                if (bm->bible >= 4 || bm->bible < 0)
                    return false;

                bible_t *bible = &data.bibles[bm->bible];

                if (bm->book >= bible->noBooks || bm->book < 0)
                    return false;

                book_t *book = &bible->books[bm->book];

                if (bm->chapter >= book->noChapters || bm->chapter < 0)
                    return false;

                chapter_t *chapter = &book->chapters[bm->chapter];

                if (bm->verse >= chapter->noVerses || bm->verse < 0)
                    return false;

                data.curBible = bm->bible;
                data.curBook = bm->book;
                data.curChapter = bm->chapter;
                data.curVerse = bm->verse;
                data.index = (int)bm->verse;

                data.page = PAGE_CHAPTER_VIEW;
                if (bookmarks)
                    free(bookmarks);
                return true;
            }
        }
        if (pad & PAD_BUTTON_B)
        {
            if (bookmarks)
                free(bookmarks);
            data.index = 0;
            data.page = PAGE_BIBLE_LIST;
            return true;
        }
    }
    return false;
}