use lazy_static::lazy_static;
use bson::doc;
use models::LocationRecord;
use crate::core::auth0::UserDetails;
use crate::core::mongo;
use crate::core::error2::Error;
use crate::core::error2::Result;
pub mod models;
use self::models::LocationPo;
lazy_static! {
pub static ref LOCATION_DB: &'static str = "app_location_db";
pub static ref LOCATION_COL: &'static str = "t_device_locations";
}
pub async fn save_locations(
client: &mongo::MongoClient,
curr_user: Option<&UserDetails>,
locations: &str,
) -> Result<usize> {
let _record = match crate::commons::parse_json_string::<Vec<LocationPo>>(locations) {
Ok(o) => o,
Err(e) => {
let error_msg = format!(
"Parse-location-data-failed: error={}, data={}",
e, locations
);
log::error!("{}", error_msg);
return Err(Error::invalid_request(error_msg));
}
};
let curr_device_id = _record
.first()
.map(|f| f.device_id.clone().unwrap_or_default())
.unwrap_or_default();
if curr_device_id.is_empty() {
return Err(Error::invalid_request("空数据或无设备id!".to_string()));
}
let filter = doc! {"device_id": curr_device_id};
let _sort = doc! {"timestamp": -1};
let list: Vec<LocationRecord> = client
.select::<LocationRecord>(*LOCATION_DB, *LOCATION_COL, filter, _sort, (0, 1))
.await?
.into_iter()
.collect();
let filtered_records: Vec<LocationPo>;
if let Some(record) = list.first() {
filtered_records = _record
.clone()
.into_iter()
.filter(|f| match f.time.cmp(&record.timestamp) {
std::cmp::Ordering::Less => false,
std::cmp::Ordering::Greater => true,
std::cmp::Ordering::Equal => false,
})
.collect();
} else {
filtered_records = _record.clone();
}
for item in filtered_records.iter() {
let record = LocationRecord::from(curr_user, item);
client
.insert_one(*LOCATION_DB, *LOCATION_COL, record)
.await?;
}
Ok(_record.len())
}
pub async fn filter_locaitons(
client: &mongo::MongoClient,
filter: mongodb::bson::Document,
pagation: (u32, u32),
) -> Result<Vec<LocationRecord>> {
let _sort = doc! {"location_id": -1};
let list = client
.select::<LocationRecord>(*LOCATION_DB, *LOCATION_COL, filter, _sort, pagation)
.await?
.into_iter()
.collect();
Ok(list)
}