/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2026 Hurry Curry! Contributors

    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 <https://www.gnu.org/licenses/>.

*/

use super::{Entity, EntityContext};
use crate::random_gauss;
use hurrycurry_data::entities::EnvironmentEffect;
use hurrycurry_locale::TrError;
use hurrycurry_protocol::PacketC;

#[derive(Clone, Debug)]
pub struct EnvironmentEffectController {
    config: EnvironmentEffect,
    next_transition: f32,
    active: bool,
}

impl EnvironmentEffectController {
    pub fn new(config: EnvironmentEffect) -> Self {
        Self {
            next_transition: config.on,
            active: false,
            config,
        }
    }
}
impl Entity for EnvironmentEffectController {
    fn tick(&mut self, c: EntityContext) -> Result<(), TrError> {
        self.next_transition -= c.dt;
        if self.next_transition < 0. {
            if self.active {
                self.next_transition += self.config.off + random_gauss() * self.config.off_stdev;
                self.active = false;
                c.game.environment_effects.remove(&self.config.name);
            } else {
                self.next_transition += self.config.on + random_gauss() * self.config.on_stdev;
                self.active = true;
                c.game.environment_effects.insert(self.config.name.clone());
            }
            c.packet_out.push_back(PacketC::Environment {
                effects: c.game.environment_effects.clone(),
            })
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct EnvironmentController(pub Vec<String>);
impl Entity for EnvironmentController {
    fn constructor(&mut self, c: EntityContext) {
        c.game.environment_effects.extend(self.0.clone());
        c.packet_out.push_back(PacketC::Environment {
            effects: c.game.environment_effects.clone(),
        })
    }
}
