use std::hash::{Hash, Hasher};
use indexmap::Equivalent;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::push::Action;
use crate::push::push_rule::PushRule;
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct SimplePushRule<T>
where
T: 'static,
{
pub actions: Vec<Action>,
pub default: bool,
pub enabled: bool,
pub rule_id: T,
}
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct SimplePushRuleInit<T> {
pub actions: Vec<Action>,
pub default: bool,
pub enabled: bool,
pub rule_id: T,
}
impl<T> From<SimplePushRuleInit<T>> for SimplePushRule<T> {
fn from(init: SimplePushRuleInit<T>) -> Self {
let SimplePushRuleInit {
actions,
default,
enabled,
rule_id,
} = init;
Self {
actions,
default,
enabled,
rule_id,
}
}
}
impl<T> Hash for SimplePushRule<T>
where
T: Hash,
{
fn hash<H: Hasher>(&self, state: &mut H) {
self.rule_id.hash(state);
}
}
impl<T> PartialEq for SimplePushRule<T>
where
T: PartialEq<T>,
{
fn eq(&self, other: &Self) -> bool {
self.rule_id == other.rule_id
}
}
impl<T> Eq for SimplePushRule<T> where T: Eq {}
impl<T> Equivalent<SimplePushRule<T>> for str
where
T: AsRef<str>,
{
fn equivalent(&self, key: &SimplePushRule<T>) -> bool {
self == key.rule_id.as_ref()
}
}
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct NewSimplePushRule<T>
where
T: ToSchema + 'static,
{
pub rule_id: T,
pub actions: Vec<Action>,
}
impl<T> NewSimplePushRule<T>
where
T: ToSchema,
{
pub fn new(rule_id: T, actions: Vec<Action>) -> Self {
Self { rule_id, actions }
}
}
impl<T> From<SimplePushRule<T>> for PushRule
where
T: Into<String>,
{
fn from(push_rule: SimplePushRule<T>) -> Self {
let SimplePushRule {
actions,
default,
enabled,
rule_id,
..
} = push_rule;
let rule_id = rule_id.into();
Self {
actions,
default,
enabled,
rule_id,
conditions: None,
pattern: None,
}
}
}
impl<T> From<NewSimplePushRule<T>> for SimplePushRule<T>
where
T: ToSchema,
{
fn from(new_rule: NewSimplePushRule<T>) -> Self {
let NewSimplePushRule { rule_id, actions } = new_rule;
Self {
actions,
default: false,
enabled: true,
rule_id,
}
}
}
impl<T> From<SimplePushRuleInit<T>> for PushRule
where
T: Into<String>,
{
fn from(init: SimplePushRuleInit<T>) -> Self {
let SimplePushRuleInit {
actions,
default,
enabled,
rule_id,
} = init;
let rule_id = rule_id.into();
Self {
actions,
default,
enabled,
rule_id,
pattern: None,
conditions: None,
}
}
}
impl<T> TryFrom<PushRule> for SimplePushRule<T>
where
T: TryFrom<String>,
{
type Error = <T as TryFrom<String>>::Error;
fn try_from(push_rule: PushRule) -> Result<Self, Self::Error> {
let PushRule {
actions,
default,
enabled,
rule_id,
..
} = push_rule;
let rule_id = T::try_from(rule_id)?;
Ok(SimplePushRuleInit {
actions,
default,
enabled,
rule_id,
}
.into())
}
}