use crate::models::users::UserID;
use crate::schema::*;
use crate::utils::time_utils::time;
use diesel::prelude::*;
use std::cmp::min;
use std::num::ParseIntError;
use std::str::FromStr;

#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct TokenID(pub i32);

impl FromStr for TokenID {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(s.parse()?))
    }
}

#[derive(Default, Queryable, Debug, Clone, serde::Serialize)]
pub struct Token {
    id: i32,
    pub name: String,
    pub time_create: i64,
    user_id: i32,
    #[serde(skip_serializing)]
    pub token_value: String,
    pub time_used: i64,
    pub max_inactivity: i32,
    ip_net: Option<String>,
    pub read_only: bool,
    pub right_account: bool,
    pub right_movement: bool,
    pub right_inbox: bool,
    pub right_file: bool,
    pub right_auth: bool,
    pub right_stats: bool,
    pub right_backup: bool,
}

impl Token {
    pub fn id(&self) -> TokenID {
        TokenID(self.id)
    }

    pub fn user_id(&self) -> UserID {
        UserID(self.user_id)
    }

    pub fn ip_net(&self) -> Option<ipnet::IpNet> {
        self.ip_net
            .as_ref()
            .map(|i| ipnet::IpNet::from_str(i).unwrap())
    }

    pub fn shall_update_time_used(&self) -> bool {
        let refresh_interval = min(600, self.max_inactivity / 10);

        (self.time_used as u64) < time() - refresh_interval as u64
    }

    pub fn is_expired(&self) -> bool {
        (self.time_used + self.max_inactivity as i64) < time() as i64
    }
}

#[derive(Insertable)]
#[diesel(table_name = tokens)]
pub struct NewToken<'a> {
    pub name: &'a str,
    pub user_id: i32,
    pub time_create: i64,
    pub time_used: i64,
    pub max_inactivity: i32,
    pub ip_net: Option<&'a str>,
    pub token_value: &'a str,
    pub read_only: bool,
    pub right_account: bool,
    pub right_movement: bool,
    pub right_inbox: bool,
    pub right_file: bool,
    pub right_auth: bool,
    pub right_stats: bool,
    pub right_backup: bool,
}
