use std::{
collections::{btree_map, BTreeMap},
ops::Deref,
};
use js_int::UInt;
use ruma_common::OwnedEventId;
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use crate::{message::TextContentBlock, relation::Reference};
#[derive(Clone, Debug, Serialize, Deserialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.poll.end", kind = MessageLike)]
pub struct PollEndEventContent {
#[serde(rename = "m.text")]
pub text: TextContentBlock,
#[serde(rename = "m.poll.results", skip_serializing_if = "Option::is_none")]
pub poll_results: Option<PollResultsContentBlock>,
#[cfg(feature = "unstable-msc3955")]
#[serde(
default,
skip_serializing_if = "ruma_common::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl PollEndEventContent {
pub fn new(text: TextContentBlock, poll_start_id: OwnedEventId) -> Self {
Self {
text,
poll_results: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: Reference::new(poll_start_id),
}
}
pub fn with_plain_text(plain_text: impl Into<String>, poll_start_id: OwnedEventId) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
poll_results: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: Reference::new(poll_start_id),
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct PollResultsContentBlock(BTreeMap<String, UInt>);
impl PollResultsContentBlock {
pub fn sorted(&self) -> Vec<(&str, UInt)> {
let mut sorted = self.0.iter().map(|(id, count)| (id.as_str(), *count)).collect::<Vec<_>>();
sorted.sort_by(|(_, a), (_, b)| b.cmp(a));
sorted
}
}
impl From<BTreeMap<String, UInt>> for PollResultsContentBlock {
fn from(value: BTreeMap<String, UInt>) -> Self {
Self(value)
}
}
impl IntoIterator for PollResultsContentBlock {
type Item = (String, UInt);
type IntoIter = btree_map::IntoIter<String, UInt>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(String, UInt)> for PollResultsContentBlock {
fn from_iter<T: IntoIterator<Item = (String, UInt)>>(iter: T) -> Self {
Self(BTreeMap::from_iter(iter))
}
}
impl Deref for PollResultsContentBlock {
type Target = BTreeMap<String, UInt>;
fn deref(&self) -> &Self::Target {
&self.0
}
}