#include "stdafx.h"
#include "overlay_home_menu_savestate.h"
#include "overlay_home_menu_components.h"
#include "Emu/system_config.h"
#include "Emu/savestate_utils.hpp"


namespace rsx
{
	namespace overlays
	{
		home_menu_savestate::home_menu_savestate(s16 x, s16 y, u16 width, u16 height, bool use_separators, home_menu_page* parent)
			: home_menu_page(x, y, width, height, use_separators, parent, get_localized_string(localized_string_id::HOME_MENU_SAVESTATE))
		{
			const bool suspend_mode = g_cfg.savestate.suspend_emu.get();

			std::unique_ptr<overlay_element> save_state = std::make_unique<home_menu_entry>(
				suspend_mode ? home_menu::fa_icon::poweroff : home_menu::fa_icon::floppy,
				get_localized_string(suspend_mode ? localized_string_id::HOME_MENU_SAVESTATE_AND_EXIT : localized_string_id::HOME_MENU_SAVESTATE_SAVE), width, text_align::left);

			add_item(save_state, [suspend_mode](pad_button btn) -> page_navigation
			{
				if (btn != pad_button::cross) return page_navigation::stay;
				rsx_log.notice("User selected savestate in home menu");
				Emu.CallFromMainThread([suspend_mode]()
				{
					if (!suspend_mode)
					{
						Emu.after_kill_callback = []() { Emu.Restart(); };

						// Make sure we keep the game window opened
						Emu.SetContinuousMode(true);
					}
					Emu.Kill(false, true);
				});
				return page_navigation::exit;
			});

			for (u32 save_index = 1; !suspend_mode && save_index <= 4; save_index++)
			{
				if (boot_current_game_savestate(true, save_index))
				{
					const localized_string_id str_id = static_cast<localized_string_id>(static_cast<usz>(localized_string_id::HOME_MENU_RELOAD_SAVESTATE) + (save_index - 1));
					std::unique_ptr<overlay_element> reload_state = std::make_unique<home_menu_entry>(home_menu::fa_icon::restart, get_localized_string(str_id), width, text_align::left);

					add_item(reload_state, [save_index](pad_button btn) -> page_navigation
					{
						if (btn != pad_button::cross)
						{
							return page_navigation::stay;
						}

						rsx_log.notice("User selected reload savestate(%u) in home menu", save_index);
						Emu.CallFromMainThread([save_index]() { boot_current_game_savestate(false, save_index); });
						return page_navigation::exit;
					});
				}
				else
				{
					break;
				}
			}

			apply_layout();
		}
	}
}
