/*
    Hurry Curry! - a game about cooking
    Copyright 2024 metamuffin
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see .
*/
use std::time::Duration;
use crate::{data::DataIndex, game::Game};
use anyhow::{anyhow, bail, Result};
use clap::{Parser, ValueEnum};
use hurrycurry_protocol::{Message, PacketC, PacketS, PlayerID};
use log::{debug, trace};
use tokio::sync::broadcast::Sender;
pub struct State {
    index: DataIndex,
    tx: Sender,
    pub game: Game,
}
#[derive(Parser)]
#[clap(multicall = true)]
enum Command {
    /// Start a new game
    Start {
        /// Gamedata specification
        #[arg(default_value = "junior")]
        spec: String,
        /// Duration in seconds
        #[arg(default_value = "420")]
        timer: u64,
    },
    /// Abort the current game
    End,
    /// Download recipe/demand/map's source declaration
    Download {
        /// Resource kind
        #[arg(value_enum)]
        r#type: DownloadType,
        /// Name
        name: String,
    },
    /// List all recipes, demands and maps
    List,
    /// Send an effect
    Effect { name: String },
    /// Reload the resource index
    Reload,
}
#[derive(ValueEnum, Clone)]
enum DownloadType {
    Map,
    Recipes,
    Demand,
}
impl State {
    pub async fn new(tx: Sender) -> Result {
        let mut index = DataIndex::default();
        index.reload()?;
        let mut game = Game::new();
        game.load(index.generate("lobby-none-none".to_string()).await?, None);
        Ok(Self { game, index, tx })
    }
    pub async fn tick(&mut self, dt: f32) -> anyhow::Result<()> {
        if self.game.tick(dt) {
            self.tx
                .send(PacketC::ServerMessage {
                    text: format!("Game finished. You reached {} points.", self.game.points),
                })
                .ok();
            self.game.load(
                self.index.generate("lobby-none-none".to_string()).await?,
                None,
            );
        }
        while let Some(p) = self.game.packet_out() {
            if matches!(p, PacketC::UpdateMap { .. } | PacketC::Position { .. }) {
                trace!("-> {p:?}");
            } else {
                debug!("-> {p:?}");
            }
            let _ = self.tx.send(p);
        }
        Ok(())
    }
    pub async fn packet_in(&mut self, player: PlayerID, packet: PacketS) -> Result> {
        match &packet {
            PacketS::Communicate {
                message: Some(Message::Text(text)),
                persist: false,
            } if let Some(command) = text.strip_prefix("/") => {
                match self.handle_command_parse(player, command).await {
                    Ok(()) => return Ok(vec![]),
                    Err(e) => {
                        return Ok(vec![PacketC::ServerMessage {
                            text: format!("{e}"),
                        }]);
                    }
                }
            }
            _ => (),
        }
        self.game.packet_in(player, packet)?;
        Ok(vec![])
    }
    async fn handle_command_parse(&mut self, player: PlayerID, command: &str) -> Result<()> {
        self.handle_command(
            player,
            Command::try_parse_from(
                shlex::split(command)
                    .ok_or(anyhow!("quoting invalid"))?
                    .into_iter(),
            )?,
        )
        .await?;
        Ok(())
    }
    async fn handle_command(&mut self, player: PlayerID, command: Command) -> Result<()> {
        match command {
            Command::Start { spec, timer } => {
                let data = self.index.generate(spec).await?;
                self.game.load(data, Some(Duration::from_secs(timer)));
            }
            Command::End => {
                self.tx
                    .send(PacketC::ServerMessage {
                        text: format!(
                            "Game was aborted by {}.",
                            self.game
                                .players
                                .get(&player)
                                .ok_or(anyhow!("player missing"))?
                                .name
                        ),
                    })
                    .ok();
                self.game.load(
                    self.index.generate("lobby-none-none".to_string()).await?,
                    None,
                );
            }
            Command::Reload => {
                self.index.reload()?;
            }
            Command::Download { r#type, name } => {
                let source = match r#type {
                    DownloadType::Map => self.index.read_map(&name).await,
                    DownloadType::Recipes => self.index.read_recipes(&name).await,
                    DownloadType::Demand => self.index.read_demands(&name).await,
                }?;
                bail!("{source}");
            }
            Command::List => {
                bail!(
                    "Maps: {:?}\nDemands: {:?}\nRecipes: {:?}",
                    self.index.maps,
                    self.index.demands,
                    self.index.recipes
                )
            }
            Command::Effect { name } => {
                self.tx
                    .send(PacketC::Communicate {
                        player,
                        message: Some(Message::Effect(name)),
                        persist: false,
                    })
                    .ok();
            }
        }
        Ok(())
    }
}