// Copyright (C) Call of Nil contributors
// SPDX-License-Identifier: AGPL-3.0-only

use crate::continent::Coord;
use crate::error::{Error, Result};
use crate::infrastructure::building::level::BuildingLevel;
use crate::infrastructure::building::{Building, StorageId};
use derive_more::{From, Into};
use nil_num::growth::growth;
use nil_util::ConstDeref;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::{Add, AddAssign, Sub, SubAssign};

/// A building that stores resources.
pub trait Storage: Building {
  fn storage_id(&self) -> StorageId;
  /// Storage capacity at the **current** level.
  fn capacity(&self, stats: &StorageStatsTable) -> Result<StorageCapacity>;
  /// Storage capacity at its **minimum** level.
  fn min_capacity(&self) -> StorageCapacity;
  /// Storage capacity at its **maximum** level.
  fn max_capacity(&self) -> StorageCapacity;
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
pub struct StorageStats {
  pub level: BuildingLevel,
  pub capacity: StorageCapacity,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
pub struct StorageStatsTable {
  id: StorageId,
  table: HashMap<BuildingLevel, StorageStats>,
}

impl StorageStatsTable {
  pub(crate) fn new(storage: &dyn Storage) -> Self {
    let max_level = storage.max_level();
    let mut table = HashMap::with_capacity(max_level.into());

    let mut capacity = f64::from(storage.min_capacity());
    let capacity_growth = growth()
      .floor(capacity)
      .ceil(storage.max_capacity())
      .max_level(max_level)
      .call();

    for level in 1..=u8::from(max_level) {
      let level = BuildingLevel::new(level);
      table.insert(
        level,
        StorageStats {
          level,
          capacity: StorageCapacity::from(capacity.ceil()),
        },
      );

      debug_assert!(capacity.is_normal());

      capacity += capacity * capacity_growth;
    }

    table.shrink_to_fit();

    Self { id: storage.storage_id(), table }
  }

  #[inline]
  pub fn id(&self) -> StorageId {
    self.id
  }

  #[inline]
  pub fn get(&self, level: BuildingLevel) -> Result<&StorageStats> {
    self
      .table
      .get(&level)
      .ok_or(Error::StorageStatsNotFoundForLevel(self.id, level))
  }
}

/// Storage capacity of a building.
#[derive(Clone, Copy, Debug, From, Into, Deserialize, Serialize, ConstDeref)]
#[derive_const(Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
pub struct StorageCapacity(u32);

impl StorageCapacity {
  #[inline]
  pub const fn new(value: u32) -> Self {
    Self(value)
  }
}

impl const From<f64> for StorageCapacity {
  fn from(value: f64) -> Self {
    Self::new(value as u32)
  }
}

impl const From<StorageCapacity> for f64 {
  fn from(value: StorageCapacity) -> Self {
    f64::from(value.0)
  }
}

impl const PartialEq<u32> for StorageCapacity {
  fn eq(&self, other: &u32) -> bool {
    self.0.eq(other)
  }
}

impl const Add for StorageCapacity {
  type Output = StorageCapacity;

  fn add(self, rhs: Self) -> Self::Output {
    Self(self.0.saturating_add(rhs.0))
  }
}

impl const Add<u32> for StorageCapacity {
  type Output = StorageCapacity;

  fn add(self, rhs: u32) -> Self::Output {
    Self(self.0.saturating_add(rhs))
  }
}

impl const AddAssign for StorageCapacity {
  fn add_assign(&mut self, rhs: Self) {
    *self = *self + rhs;
  }
}

impl const AddAssign<u32> for StorageCapacity {
  fn add_assign(&mut self, rhs: u32) {
    *self = *self + rhs;
  }
}

impl const Sub for StorageCapacity {
  type Output = StorageCapacity;

  fn sub(self, rhs: Self) -> Self::Output {
    Self(self.0.saturating_sub(rhs.0))
  }
}

impl const Sub<u32> for StorageCapacity {
  type Output = StorageCapacity;

  fn sub(self, rhs: u32) -> Self::Output {
    Self(self.0.saturating_sub(rhs))
  }
}

impl const SubAssign for StorageCapacity {
  fn sub_assign(&mut self, rhs: Self) {
    *self = *self - rhs;
  }
}

impl const SubAssign<u32> for StorageCapacity {
  fn sub_assign(&mut self, rhs: u32) {
    *self = *self - rhs;
  }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[derive_const(Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
pub struct OverallStorageCapacity {
  pub silo: StorageCapacity,
  pub warehouse: StorageCapacity,
}

impl const Add for OverallStorageCapacity {
  type Output = OverallStorageCapacity;

  fn add(mut self, rhs: Self) -> Self::Output {
    self += rhs;
    self
  }
}

impl const AddAssign for OverallStorageCapacity {
  fn add_assign(&mut self, rhs: Self) {
    self.silo += rhs.silo;
    self.warehouse += rhs.warehouse;
  }
}

#[derive(Copy, Debug, From, Into, ConstDeref)]
#[derive_const(Clone, Default, PartialEq, PartialOrd)]
pub struct StorageCapacityWeight(f64);

#[derive(Clone, Debug)]
pub struct OverallStorageCapacityWeight {
  pub coord: Coord,
  pub silo: StorageCapacityWeight,
  pub warehouse: StorageCapacityWeight,
}

impl OverallStorageCapacityWeight {
  pub const fn new(coord: Coord) -> Self {
    Self {
      coord,
      silo: StorageCapacityWeight::default(),
      warehouse: StorageCapacityWeight::default(),
    }
  }
}
