thisweek_core/
week_info.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use crate::{calendar::Calendar, language::Language, prelude::Result as AppResult};
use serde::Serialize;

#[derive(Debug, Serialize, Clone, Default)]
pub struct WeekInfo {
    calendar: Calendar,
    language: Language,
    dates: Vec<DateView>,
    direction: String,
    month_year_info: String,
}

#[derive(Serialize, Clone)]
pub struct Date {
    pub calendar: Calendar,
    pub weekday: u32,
    pub day: u32,
    pub month: u32,
    pub year: i32,
}

#[derive(Debug, Serialize, Clone, Default)]
pub struct DateView {
    pub unix_day: i32,
    pub day: String,
    pub month: String,
    pub year: String,
    pub weekday: String,
    pub full_format: String,
}

impl WeekInfo {
    pub fn from_unix_start_end_days(
        start_day: i32,
        end_day: i32,
        today: i32,
        calendar: Calendar,
        language: Language,
    ) -> AppResult<Self> {
        let direction = calendar.into_direction();
        let dates = calendar.get_dates_view(start_day, end_day, &language)?;
        let today_view = calendar.get_date_view(today, &language);
        let month_year_info = Self::calculate_month_year_info(&dates, &today_view);
        Ok(WeekInfo {
            calendar,
            dates,
            direction,
            language,
            month_year_info,
        })
    }

    // note: this can be better generated by specific calendars
    fn calculate_month_year_info(dates: &Vec<DateView>, today: &DateView) -> String {
        let first_day_year = dates.first().unwrap().year.clone();
        let last_day_year = dates.last().unwrap().year.clone();
        let first_day_month = dates.first().unwrap().month.clone();
        let last_day_month = dates.last().unwrap().month.clone();
        let today_year = today.year.clone();
        let today_month = today.month.clone();

        if first_day_month == last_day_month && first_day_year == today_year {
            return first_day_month.to_string();
        }

        if first_day_month != last_day_month
            && first_day_year == today_year
            && last_day_year == today_year
        {
            return format!("{} - {}", first_day_month, last_day_month);
        }

        if first_day_year != last_day_year {
            return format!(
                "{} {} - {} {}",
                first_day_month, first_day_year, last_day_month, last_day_year
            );
        }

        if first_day_month == last_day_month && first_day_year == last_day_year {
            return format!("{} {}", first_day_month, first_day_year);
        }

        format!(
            "{} {} - {} {}",
            first_day_month, first_day_year, last_day_month, last_day_year
        )
    }
}