#include "menu.h"

int menu(SDL_Renderer* renderer){
    int SCREEN_WIDTH, SCREEN_HEIGHT;
    SDL_GetRendererOutputSize(renderer,&SCREEN_WIDTH,&SCREEN_HEIGHT);

    bool quit = false;
	SDL_Event e;

	Texture txLogo;
	txLogo.setRenderer(renderer);
    txLogo.loadTexture("textures/title.png");

    int logoVmargin = 40;

    SDL_Rect logo = {(SCREEN_WIDTH/2)-txLogo.getWidth()/2,logoVmargin,txLogo.getWidth(),txLogo.getHeight()};

    int btnSpc = SCREEN_HEIGHT - (logo.y + logo.h);
	int buttonNum = 3;
	SDL_Rect button[buttonNum];
	int btnWidth = SCREEN_WIDTH/3;
	int btnHeight = btnSpc/buttonNum/2;
	int spc = (btnSpc-buttonNum*btnHeight)/(buttonNum+1);

    for(int i = 0; i < buttonNum; i++){
        button[i].x = SCREEN_WIDTH/2-btnWidth/2;
        button[i].y = ((i+1)*spc+i*btnHeight)+SCREEN_HEIGHT-btnSpc;
        button[i].w = btnWidth;
        button[i].h = btnHeight;
    }

	int select = 0;
	bool wait = 0;
	const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL);

	while(!quit){
		while(SDL_PollEvent(&e)!=0){
			if(e.type == SDL_QUIT){
				quit = true;
			}
		}
		SDL_SetRenderDrawColor(renderer,100,200,200,0xFF);
		SDL_RenderClear(renderer);

		int dir = 0;
		if(currentKeyStates[SDL_SCANCODE_UP]) dir--;
		if(currentKeyStates[SDL_SCANCODE_DOWN])dir++;

		if(dir != 0){
            if(!wait) select += dir;
            wait = true;
		}
		else wait = false;

		if(select >= buttonNum) select = 0;
		if(select < 0) select = buttonNum-1;

        txLogo.render(&logo);

        for(int i = 0; i < buttonNum; i++){
            if(static_cast<int>(select) == i){
                    SDL_SetRenderDrawColor(renderer,80,80,80,0xFF);
                    if(currentKeyStates[SDL_SCANCODE_SPACE]) SDL_SetRenderDrawColor(renderer,200,200,200,0xFF);
            }
            else SDL_SetRenderDrawColor(renderer,128,128,128,0xFF);

            SDL_RenderFillRect(renderer,&button[i]);
        }
        if(currentKeyStates[SDL_SCANCODE_SPACE]){
            if(select ==  0) return 1;
            else if(select == 1) return 2;
            else if(select == 2) break;
        }

		SDL_RenderPresent(renderer);
	}

	return -1;
}
