#include <memory>

#define SDL_MAIN_USE_CALLBACKS
#include <SDL3/SDL_main.h>

#include "engine/engine.h"
#include "screens/mainscreen.h"
#include "screens/levelselectionscreen.h"
#include "screens/gamescreen.h"
#include "screens/authorscreen.h"
#include "screens/setupscreen.h"
#include "screens/recordscreen.h"
#include "screens/launcher.h"
#include "engine/tools/Profiler.h"
#include "engine/locale.h"

SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv){
    SDL_SetHint(SDL_HINT_ORIENTATIONS, "Portrait PortraitUpsideDown");

    if (!Engine::init(360,740)) return SDL_APP_FAILURE;


    Profiler profiler;
    profiler.start();

    int *count=NULL;
    std::string locale = "en";
    SDL_Locale **locales = SDL_GetPreferredLocales(count);
    if (locales){
        locale = std::string(locales[0]->country);
    }
    SDL_free(locales);
    Locale::getInstance()->init(locale);
    profiler.timestamp("load locale: "+locale);


    auto launcher = new Launcher();
    Engine::setActiveScreen("launcher");
    profiler.timestamp("load launcher");
    Engine::draw();

    //SDL_Delay(3000);
    //return  SDL_APP_SUCCESS;

    profiler.start();
    auto *mainscreen = new MainScreen();
    profiler.timestamp("load MainScreen");

    auto *levelselection = new LevelSelectionScreen();
    profiler.timestamp("load LevelSelectionScreen");

    auto *game = new GameScreen();
    profiler.timestamp("load GameScreen");

    auto *author = new AuthorScreen();
    profiler.timestamp("load AuthorScreen");

    auto *setup = new SetupScreen();
    profiler.timestamp("load SetupScreen");

    auto *records = new RecordScreen();
    profiler.timestamp("load RecordScreen");

    Engine::setActiveScreen("main");
    delete launcher;

    profiler.stop("Инициализация окон");


    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppIterate(void *appstate){
    Engine::logic();
    Engine::draw();
    return  SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event){
    Engine::event(*event);
    switch (event->type) {
        case SDL_EVENT_QUIT: {
            return SDL_APP_SUCCESS;
            break;
        }
    }
    return  SDL_APP_CONTINUE;
}

void SDL_AppQuit(void *appstate, SDL_AppResult result){
    Engine::stop();
}