thisweek_core/
week_info.rs

1use crate::{calendar::Calendar, language::Language, prelude::Result as AppResult};
2use serde::Serialize;
3
4#[derive(Debug, Serialize, Clone, Default)]
5pub struct WeekInfo {
6    calendar: Calendar,
7    language: Language,
8    dates: Vec<DateView>,
9    direction: String,
10    month_year_info: String,
11}
12
13#[derive(Serialize, Clone)]
14pub struct Date {
15    pub calendar: Calendar,
16    pub weekday: u32,
17    pub day: u32,
18    pub month: u32,
19    pub year: i32,
20}
21
22#[derive(Debug, Serialize, Clone, Default)]
23pub struct DateView {
24    pub unix_day: i32,
25    pub day: String,
26    pub month: String,
27    pub year: String,
28    pub weekday: String,
29    pub full_format: String,
30}
31
32impl WeekInfo {
33    pub fn from_unix_start_end_days(
34        start_day: i32,
35        end_day: i32,
36        today: i32,
37        calendar: Calendar,
38        language: Language,
39    ) -> AppResult<Self> {
40        let direction = calendar.into_direction();
41        let dates = calendar.get_dates_view(start_day, end_day, &language)?;
42        let today_view = calendar.get_date_view(today, &language);
43        let month_year_info = Self::calculate_month_year_info(&dates, &today_view);
44        Ok(WeekInfo {
45            calendar,
46            dates,
47            direction,
48            language,
49            month_year_info,
50        })
51    }
52
53    // note: this can be better generated by specific calendars
54    fn calculate_month_year_info(dates: &[DateView], today: &DateView) -> String {
55        let first_day_year = dates.first().unwrap().year.clone();
56        let last_day_year = dates.last().unwrap().year.clone();
57        let first_day_month = dates.first().unwrap().month.clone();
58        let last_day_month = dates.last().unwrap().month.clone();
59        let today_year = today.year.clone();
60        // let today_month = today.month.clone();
61
62        if first_day_month == last_day_month && first_day_year == today_year {
63            return first_day_month.to_string();
64        }
65
66        if first_day_month != last_day_month
67            && first_day_year == today_year
68            && last_day_year == today_year
69        {
70            return format!("{} - {}", first_day_month, last_day_month);
71        }
72
73        if first_day_year != last_day_year {
74            return format!(
75                "{} {} - {} {}",
76                first_day_month, first_day_year, last_day_month, last_day_year
77            );
78        }
79
80        if first_day_month == last_day_month && first_day_year == last_day_year {
81            return format!("{} {}", first_day_month, first_day_year);
82        }
83
84        format!(
85            "{} {} - {} {}",
86            first_day_month, first_day_year, last_day_month, last_day_year
87        )
88    }
89}