#include <app.h>
#include <GLFW/glfw3.h>
#include <render/primitives.h>
#include "noteManager.hpp"
#include "level.h"

const vec4f colors[4] = {
    color::blue,
    color::red,
    color::orange,
    color::green
};

const float showTime = 1.5;
const float hideTime = 0.15;
const float pressWindow = 0.09;
const float perfectWindow = 0.05;
const float badTime = 0.12;

namespace game {

NoteManager::NoteManager(Level *root)
{
    this->startTime = 0;
    this->shouldChangeState = false;
    this->longActive = false;
    this->root = root;
}

void NoteManager::Load(std::list<noteInfo*> *timeline) {
    this->timeline = timeline;
    this->cursor = this->timeline->begin();
}

void NoteManager::Start()
{
    if (this->startTime) {
        this->startTime = glfwGetTime() - currentTime;
    } else {
        this->startTime = glfwGetTime();
    }

    this->playing = true;
}

void NoteManager::Pause()
{
    this->playing = false;
}

void NoteManager::Reset(float songLength)
{
    this->songLength = songLength;
    this->playing = false;
    this->startTime = 0;
    this->currentTime = 0;

    this->activeNotes.clear();
    this->visibleNotes.clear();
    this->cursor = this->timeline->begin();
}

void NoteManager::Update(const buttonState &state)
{
    if (!this->playing) {
        return;
    }

    float calibration = App::GetConfig()->getConfig().calibration;
    this->currentTime = glfwGetTime() - this->startTime - calibration;

    if (this->currentTime > songLength) {
        return;
    }

    this->UpdateNoteList();

    if (!state.level || state.button != controlState.button) {
        this->shouldChangeState = false;
    }

    this->controlState = state;

    if (!(activeNotes.empty() || this->shouldChangeState)) {
        this->UpdateNoteAction();
    }

    for(auto i: visibleNotes) {
        i->Update();
    }
}

void NoteManager::UpdateNoteList()
{
    for (auto i: notesForRemove) {
        this->activeNotes.remove(i);
        this->visibleNotes.remove(i);
        delete i;
    }

    notesForRemove.clear();

    while (this->cursor != timeline->end()) {
        if ((*cursor)->time > currentTime + showTime) {
            break;
        }

        this->CreateNote(*this->cursor);
        this->cursor++;
    }

    while (!this->activeNotes.empty()) {

        auto currentNote = this->activeNotes.front();

        float endTime = currentNote->info->time;

        if (currentNote->info->type == 1 && this->longActive) {
            endTime += currentNote->info->duration;
        }

        if (endTime > currentTime - hideTime) {
            break;
        }

        root->AddNoteResult(NoteResult::miss, currentNote->info);
        currentNote->Miss();
        this->activeNotes.pop_front();

        if (this->longActive) {
            this->longActive = false;
            this->shouldChangeState = true;
        }
    }
}

void NoteManager::UpdateNoteAction()
{
    Note *currentNote = activeNotes.front();

    float timeDiff = fabs(currentNote->info->time - currentTime);

    uint32_t flags = root->GetFlags();

    if (flags&(uint32_t)StartFlags::hardenedTimings) {
        timeDiff *= 1.5;
    } else if (flags&(uint32_t)StartFlags::relaxedTimings) {
        timeDiff /= 1.5;
    }

    if (timeDiff > hideTime && !this->longActive) {

        if (this->controlState.level) {
            this->shouldChangeState = true;
        }

        return;
    }

    if (controlState.level) {

        if (currentNote->info->type == 1 && this->longActive) {

            if (currentNote->info->time + currentNote->info->duration + pressWindow < currentTime) {
                activeNotes.pop_front();
                this->RemoveNote(currentNote);
                this->longActive = false;
                this->shouldChangeState = true;
                root->AddNoteResult(NoteResult::miss, currentNote->info);
            }
            return;
        }

        if (timeDiff > pressWindow) {
            activeNotes.pop_front();
            currentNote->Miss();

            if (timeDiff < badTime) {
                root->AddNoteResult(NoteResult::almost, currentNote->info);
            } else {
                root->AddNoteResult(NoteResult::miss, currentNote->info);
            }

            return;
        } else if (controlState.button != currentNote->info->button) {
            activeNotes.pop_front();
            this->RemoveNote(currentNote);
            root->AddNoteResult(NoteResult::wrong, currentNote->info);
            return;
        }

        switch (currentNote->info->type) {
        case 0:
            this->shouldChangeState = true;
            currentNote->Hit();
            activeNotes.pop_front();

            if (timeDiff < perfectWindow) {
                root->AddNoteResult(NoteResult::great, currentNote->info);
            } else {
                root->AddNoteResult(NoteResult::ok, currentNote->info);
            }
            return;
        case 1:
            this->longActive = true;
            currentNote->active = true;

            if (timeDiff < perfectWindow) {
                root->AddNoteResult(NoteResult::great, currentNote->info);
            } else {
                root->AddNoteResult(NoteResult::ok, currentNote->info);
            }

            return;
        case 2:
            if (controlState.level == 2) {
                this->shouldChangeState = true;
                activeNotes.pop_front();
                currentNote->Hit();
                if (timeDiff < perfectWindow) {
                    root->AddNoteResult(NoteResult::great, currentNote->info);
                } else {
                    root->AddNoteResult(NoteResult::ok, currentNote->info);
                }
                return;
            }
        }

    } else if (currentNote->info->type == 1 && this->longActive) {
        timeDiff = fabs(currentNote->info->time + currentNote->info->duration - currentTime);

        if (timeDiff > pressWindow) {

            activeNotes.pop_front();
            this->RemoveNote(currentNote);

            if (timeDiff < badTime) {
                root->AddNoteResult(NoteResult::almost, currentNote->info);
            } else {
                root->AddNoteResult(NoteResult::miss, currentNote->info);
            }
            this->longActive = false;
            return;
        } else {
            activeNotes.pop_front();
            currentNote->Hit();
            if (timeDiff < perfectWindow) {
                root->AddNoteResult(NoteResult::great, currentNote->info);
            } else {
                root->AddNoteResult(NoteResult::ok, currentNote->info);
            }
            this->longActive = false;
            this->shouldChangeState = true;
            return;
        }

    }
}

void NoteManager::Render()
{
    for (auto i: visibleNotes) {
        i->RenderEffects();
    }

    render::setBlendMode(render::blendMode::normal);

    for (auto i = visibleNotes.rbegin(); i != visibleNotes.rend(); i++) {
        (*i)->RenderPlaceholder();
    }

    for (auto i: visibleNotes) {
        i->Render();
    }
}

void NoteManager::CreateNote(noteInfo *info)
{
    Note *note = new Note(this, info);

    this->activeNotes.push_back(note);
    this->visibleNotes.push_back(note);
}

void NoteManager::RemoveNote(Note *note)
{
    this->notesForRemove.insert(note);
}

}
