#include "gamestates.h"
#include "jgame.h"

namespace gamestate
{
    namespace menu
    {
        draw::surface *fondo = nullptr;
        draw::surface *cursor = nullptr;
        int exit = 0;

        bool loop();


        void init()
        {
            exit = 0;
            fondo = draw::loadSurface("menuprin.gif", true);
            cursor = draw::loadSurface("cursor.gif");

            if (audio::getMusicState() != audio::music_state::MUSIC_PLAYING) {
                audio::playMusic(audio::loadMusic("mus3.ogg"));
            }

            draw::setSource(fondo);
            draw::draw(0,0,320,200,0,0);
            draw::fadein();

            game::setState(&gamestate::menu::loop);
        }

        bool loop()
        {
            if (exit) {
                if (!draw::isfading()) {
                    draw::freeSurface(fondo);
                    draw::freeSurface(cursor);
                    if (exit==1) gamestate::sequence::init();
                    //if (exit==2) gamestate::password::init();
                }
                draw::render();
                return true;
            }
            const int x = input::mouseX();
            const int y = input::mouseY();

            draw::setTrans(255);
            draw::setSource(fondo);
            draw::draw(0, 0, 320, 200, 0, 0);

            draw::setTrans(0);
            draw::setSource(cursor);
            draw::draw(x, y, cursor->w, cursor->h, 0, 0);

            draw::render();

            if (input::mouseClk(1))
            {
                if (x >= 200 && y >= 100 && x <= 270 && y <= 120) {
                    draw::fadeout();
                    game::setConfig("fase", 0);
                    exit = 1;
                    return true;
                } else if (x >= 175 && y >= 125 && x <= 290 && y <= 145) {
                    draw::fadeout();
                    game::setConfig("fase", 0);
                    exit = 2;
                    return true;
                } else if (x >= 200 && y >= 150 && x <= 265 && y <= 170) {
                    return false;
                }
            }

            return true;
        }

    }
}