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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use std::fmt;

use ggez::{graphics, Context, GameResult};

use crate::ChessGui;

/// Indicate how align the text (GUI).
#[derive(Copy, Clone, Eq, PartialEq, Default, Debug)]
pub enum Align {
    Left,
    Right,
    #[default]
    Center,
}

/// A struct of button for interact with the GUI.
#[derive(Copy, Clone)]
pub struct Button {
    /// The id is not unique, it's just a name to identify it.
    pub id: &'static str,
    enable: bool,
    rect: graphics::Rect,
    image_path: Option<&'static str>,
    color: graphics::Color,
    text: &'static str,
    align: Align,
    func: Option<fn(&mut ChessGui)>,
}

impl Button {
    /// Create a new [`Button`].
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: &'static str,
        enable: bool,
        rect: graphics::Rect,
        color: graphics::Color,
        text: &'static str,
        align: Align,
        func: Option<fn(&mut ChessGui)>,
    ) -> Self {
        Button {
            id,
            enable,
            rect,
            image_path: None,
            color,
            text,
            align,
            func,
        }
    }

    /// Verify if the button is enable.
    pub fn is_enable(&self) -> bool {
        self.enable
    }

    /// Enable the button.
    pub fn enable(&mut self) {
        self.enable = true;
    }

    /// Disable the button.
    pub fn disable(&mut self) {
        self.enable = false;
    }

    /// Draw the image at the given path rather than a rectangle.
    pub fn set_image(&mut self, path: Option<&'static str>) -> Self {
        self.image_path = path;
        *self
    }

    /// Verify if a coordinate is in the button.
    pub fn contains(&self, x: f32, y: f32) -> bool {
        self.rect.contains([x, y])
    }

    /// Draw the button in the [`Context`].
    pub fn draw(&self, ctx: &mut Context, font_path: &str, font_scale: f32) -> GameResult {
        if self.enable {
            if self.image_path.is_some() {
                self.draw_image(ctx)?;
            } else {
                self.draw_rect(ctx)?;
                self.draw_text(ctx, font_path, font_scale)?;
            }
        }
        Ok(())
    }

    /// Draw the button without text.
    fn draw_rect(&self, ctx: &mut Context) -> GameResult {
        let mesh = graphics::MeshBuilder::new()
            .rectangle(graphics::DrawMode::stroke(3.0), self.rect, self.color)?
            .build(ctx)?;
        graphics::draw(ctx, &mesh, graphics::DrawParam::default())?;
        Ok(())
    }

    /// Draw the text of the button.
    fn draw_text(&self, ctx: &mut Context, font_path: &str, font_scale: f32) -> GameResult {
        let font = graphics::Font::new(ctx, font_path)?;
        let text = graphics::Text::new((self.text, font, font_scale));
        let dest_point = match self.align {
            Align::Left => [self.rect.x, self.rect.y],
            Align::Right => [
                self.rect.x + self.rect.w - text.width(ctx),
                self.rect.y + self.rect.h - text.height(ctx),
            ],
            Align::Center => [
                self.rect.x + (self.rect.w - text.width(ctx)) / 2.0,
                self.rect.y + (self.rect.h - text.height(ctx)) / 2.0,
            ],
        };
        graphics::draw(ctx, &text, (dest_point, self.color))?;
        Ok(())
    }

    /// Draw the button without text.
    fn draw_image(&self, ctx: &mut Context) -> GameResult {
        let image = graphics::Image::new(ctx, self.image_path.unwrap()).expect("Image load error");
        let image_scale = [
            self.rect.w / image.width() as f32,
            self.rect.h / image.height() as f32,
        ];
        let dp = graphics::DrawParam::new()
            .dest(self.rect.point())
            .scale(image_scale);
        graphics::draw(ctx, &image, dp)?;
        Ok(())
    }

    /// Call the func when the button is clicked.
    pub fn clicked(&self, chess_gui: &mut ChessGui) {
        if self.enable {
            if let Some(func) = self.func {
                func(chess_gui);
            }
        }
    }
}

impl fmt::Display for Button {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.id)
    }
}

impl fmt::Debug for Button {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.id)
    }
}