// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use egui::TextEdit;
use glium::Frame as GliumFrame;

use super::common::{Common, CommonGs};

use crate::app::{App, config::{self, Config}};
use crate::app::gui::{GuiState, style::{UiExt, FontSize, H4_SIZE}, port_edit::PortEdit};
use crate::net::{Address, serp::request::PlayRequest};

pub struct PsEnterAddress {
	common: Common,
	port: PortEdit,
}

impl PsEnterAddress {
	pub fn new(config: &Config) -> PsEnterAddress {
		PsEnterAddress {
			common: Common::new(),
			port: PortEdit::new(config.gui.port),
		}
	}
}

impl CommonGs for PsEnterAddress {
	fn common(&mut self) -> &mut Common { &mut self.common }

	fn loop_iter(&mut self, app: &mut App, frame: &mut GliumFrame) -> bool {
		let config = &mut app.config.borrow_mut();

		let res = GuiState::update(&mut app.gui, "ps-enter-address", &app.window, |ctx, ui| {
			ui.h1("Enter Address").no_bottom_padding().add();

			ui.h3("Host").add();
			config::set_changed!(config, ui.add(TextEdit::singleline(&mut config.gui.host).font_size(H4_SIZE)).changed());

			ui.h3("Game ID").add();
			config::set_changed!(config, ui.add(TextEdit::singleline(&mut config.gui.game_id).font_size(H4_SIZE)).changed());

			ui.h3("Port").add();
			let port = self.port.add(ui);

			ui.add_space(30.0);
			config::set_changed!(config, ui.checkbox(&mut config.gui.spectate, "Join as Spectator").changed());
			ui.add_space(15.0);

			if let Some(starter) = self.common.connection_starter() && let Some(port) = port {
				if config.gui.port != port {
					config.changed();
				}

				config.gui.port = port;

				if ui.b2(config.gui.play_button_text()).clicked() {
					let addr = Address { host: Box::from(config.gui.host.as_str()), port };
					let request = PlayRequest::new(config.gui.game_id.to_shared(), config.gui.spectate, config.get_style());
					starter.connect(app.endpoint.get(), addr, request);
				}
			} else {
				ui.b2_enabled(config.gui.play_button_text(), false);
			}

			self.common.finish_update(ctx, ui, None);
		});
		self.common.after_gui_update(res);

		app.gui.render(&app.display, frame);

		false
	}
}
