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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use std::collections::BTreeMap;

use gloo::console;
use yew::{html, Component, Context, Html, Properties};
use yew_router::prelude::Link;

use crate::components::admin_menu::{Entity, EntityType, GetError};
use crate::components::alpha_warning_banner;
use crate::constants::{CSS_BREADCRUMB_ITEM, CSS_BREADCRUMB_ITEM_ACTIVE, CSS_CELL, CSS_TABLE};
use crate::utils::{do_alert_error, do_page_header, init_request};
use crate::views::AdminRoute;

impl From<GetError> for AdminListGroupsMsg {
    fn from(ge: GetError) -> Self {
        AdminListGroupsMsg::Failed {
            emsg: ge.err,
            kopid: None,
        }
    }
}

pub struct AdminListGroups {
    state: GroupsViewState,
}

// callback messaging for this confused pile of crab-bait
pub enum AdminListGroupsMsg {
    /// When the server responds and we need to update the page
    Responded {
        response: BTreeMap<String, Entity>,
    },
    Failed {
        emsg: String,
        kopid: Option<String>,
    },
}

enum GroupsViewState {
    /// waiting for the page to load
    Loading,
    /// server has responded
    Responded { response: BTreeMap<String, Entity> },
    /// failed to pull the details
    #[allow(dead_code)]
    Failed {
        // TODO: use this
        emsg: String,
        kopid: Option<String>,
    },
    #[allow(dead_code)]
    /// Not authorized to pull the details
    NotAuthorized {}, // TODO: use this
}

#[derive(PartialEq, Properties, Eq)]
pub struct AdminListGroupsProps {
    // for filtering and pagination
    // #[allow(dead_code)]
    // search: Option<String>,
    // #[allow(dead_code)]
    // page: Option<u32>,
}

/// Pulls all accounts (service or person-class) from the backend and returns a HashMap
/// with the "name" field being the keys, for easy human-facing sortability.
pub async fn get_groups() -> Result<AdminListGroupsMsg, GetError> {
    let mut all_groups = BTreeMap::new();

    // we iterate over these endpoints
    let endpoints = [("/v1/group", EntityType::Group)];

    for (endpoint, object_type) in endpoints {
        let request = init_request(endpoint);
        let response = match request.send().await {
            Ok(value) => value,
            Err(error) => {
                return Err(GetError {
                    err: format!("{:?}", error),
                })
            }
        };
        #[allow(clippy::panic)]
        let data: Vec<Entity> = match response.json().await {
            Ok(value) => value,
            Err(error) => panic!("Failed to grab the group data into JSON: {:?}", error),
        };

        for entity in data.iter() {
            let mut new_entity = entity.to_owned();
            new_entity.object_type = object_type.clone();

            // first we try the short name and, if that isn't there then just use the SPN...
            #[allow(clippy::expect_used)]
            let entity_id = match entity.attrs.name.first() {
                Some(value) => value.to_string(),
                None => entity
                    .attrs
                    .spn
                    .first()
                    .expect("Failed to grab the SPN for a group.")
                    .to_string(),
            };
            all_groups.insert(entity_id.to_string(), new_entity);
        }
    }

    Ok(AdminListGroupsMsg::Responded {
        response: all_groups,
    })
}

impl Component for AdminListGroups {
    type Message = AdminListGroupsMsg;
    type Properties = AdminListGroupsProps;

    fn create(ctx: &Context<Self>) -> Self {
        // TODO: work out the querystring thing so we can just show x number of elements
        // console::log!("query: {:?}", location().query);

        // start pulling the account data on startup
        ctx.link().send_future(async move {
            match get_groups().await {
                Ok(v) => v,
                Err(v) => v.into(),
            }
        });
        AdminListGroups {
            state: GroupsViewState::Loading,
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        html! {
            <>
              {do_page_header("Group Administration")}

              { alpha_warning_banner() }
        <div id={"grouplist"}>
        {self.view_state(ctx)}
        </div>
        </>
        }
    }

    fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            AdminListGroupsMsg::Responded { response } => {
                // TODO: do we paginate here?
                #[cfg(test)]
                for key in response.keys() {
                    console::debug!(
                        "response: {:?}",
                        serde_json::to_string(response.get(key).unwrap()).unwrap()
                    );
                }
                self.state = GroupsViewState::Responded { response };
                return true;
            }
            AdminListGroupsMsg::Failed { emsg, kopid } => {
                // TODO: make this push a view state
                console::log!("emsg: {:?}", emsg);
                console::log!("kopid: {:?}", kopid);
            }
        }
        false
    }
}

impl AdminListGroups {
    /// output the information based on what's in the current state
    fn view_state(&self, _ctx: &Context<Self>) -> Html {
        match &self.state {
            GroupsViewState::Loading => {
                html! {"Waiting on the groups list to load..."}
            }

            GroupsViewState::Responded { response } => {
                let scope_col = "col";

                html!(
                  <table class={CSS_TABLE}>
                  <thead>
                    <tr>
                      <th scope={scope_col}>{"Name"}</th>
                      <th scope={scope_col}>{"Description"}</th>
                    </tr>
                  </thead>

                  {
                    response.keys().map(|name| {
                        #[allow(clippy::expect_used)]
                      let group: &Entity = response.get(name).expect("Couldn't get group key when it was just in the iter...");

                        let description: String = match group.attrs.description.first() {
                          Some(value) => value.to_string(),
                          None => String::from(""),
                        };
                        let uuid: String = match group.attrs.uuid.first() {
                            Some(value) => value.to_string(),
                            None => {
                                console::error!("Group without a UUID?", format!("{:?}", group).to_string());
                                String::from("GROUP WITHOUT A UUID!")
                            }
                        };

                        html!{
                          <tr key={uuid.clone()}>
                          <td class={CSS_CELL} scope={scope_col}>
                          <Link<AdminRoute> to={AdminRoute::ViewGroup{uuid:{uuid.clone()}}} >{name}</Link<AdminRoute>></td>
                          <td class={CSS_CELL}>{description}</td>
                          </tr>
                        }
                    }).collect::<Html>()
                  }
                  </table>
                )
            }

            GroupsViewState::Failed { emsg, kopid } => {
                console::error!("Failed to pull details", format!("{:?}", kopid));
                html!(
                    <>
                    {do_alert_error("Failed to Query Groups", Some(emsg))}
                    </>
                )
            }
            GroupsViewState::NotAuthorized {} => {
                do_alert_error("You're not authorized to see this page!", None)
            }
        }
    }
}

#[derive(Properties, PartialEq, Eq, Clone)]
pub struct AdminViewGroupProps {
    pub uuid: String,
}

// callback messaging for group detail view
pub enum AdminViewGroupMsg {
    /// When the server responds and we need to update the page
    Responded { response: Entity },
    #[allow(dead_code)]
    Failed { emsg: String, kopid: Option<String> },
    #[allow(dead_code)]
    NotAuthorized {},
}

impl From<GetError> for AdminViewGroupMsg {
    fn from(ge: GetError) -> Self {
        AdminViewGroupMsg::Failed {
            emsg: ge.err,
            kopid: None,
        }
    }
}

enum GroupViewState {
    /// waiting for the page to load
    Loading,
    /// server has responded
    Responded { response: Entity },
    /// failed to pull the details
    #[allow(dead_code)]
    Failed {
        // TODO: use this
        emsg: String,
        kopid: Option<String>,
    },
    #[allow(dead_code)]
    /// Not authorized to pull the details
    NotAuthorized {}, // TODO: use this
}

pub struct AdminViewGroup {
    state: GroupViewState,
}

impl Component for AdminViewGroup {
    type Message = AdminViewGroupMsg;
    type Properties = AdminViewGroupProps;

    fn create(ctx: &Context<Self>) -> Self {
        let uuid = ctx.props().uuid.clone();
        // TODO: start pulling the group details then send the msg blep blep
        ctx.link().send_future(async move {
            match get_group(&uuid).await {
                Ok(v) => v,
                Err(v) => v.into(),
            }
        });

        AdminViewGroup {
            state: GroupViewState::Loading,
        }
    }

    fn view(&self, _ctx: &Context<Self>) -> Html {
        match &self.state {
            GroupViewState::Loading => html! {"Loading..."},
            GroupViewState::Responded { response } => {
                let group_name = match response.attrs.name.first() {
                    Some(value) => value.as_str(),
                    None => {
                        // TODO: this should throw an error
                        "No Group Name?"
                    }
                };
                let page_title = format!("Group: {}", group_name);

                let group_uuid = match response.attrs.uuid.first() {
                    Some(value) => value.clone(),
                    None => String::from("Error querying UUID!"),
                };
                html! {
                    <>
                    <ol class="breadcrumb">
                    <li class={CSS_BREADCRUMB_ITEM}><Link<AdminRoute> to={AdminRoute::AdminMenu}>{"Admin"}</Link<AdminRoute>></li>
                    <li class={CSS_BREADCRUMB_ITEM}><Link<AdminRoute> to={AdminRoute::AdminListGroups}>{"Groups"}</Link<AdminRoute>></li>
                    <li class={CSS_BREADCRUMB_ITEM_ACTIVE} aria-current="page">{group_name}</li>
                    </ol>
                    {do_page_header(&page_title)}
                    <p>{"UUID: "}{group_uuid}</p>
                    // TODO: pull group membership and show members
                    <p>{"Group Membership will show up here soon..."}</p>
                    </>
                }
            }
            GroupViewState::Failed { emsg, kopid } => do_alert_error(
                emsg,
                Some(
                    kopid
                        .as_ref()
                        .unwrap_or(&String::from("unknown operation ID")),
                ),
            ),
            GroupViewState::NotAuthorized {} => {
                do_alert_error("You are not authorized to view this page!", None)
            }
        }
    }

    fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            AdminViewGroupMsg::Responded { response } => {
                self.state = GroupViewState::Responded { response };
                true
            }
            AdminViewGroupMsg::Failed { emsg, kopid } => {
                self.state = GroupViewState::Failed { emsg, kopid };
                true
            }
            AdminViewGroupMsg::NotAuthorized {} => {
                self.state = GroupViewState::NotAuthorized {};
                true
            }
        }
    }
}

/// pull the details for a single group by UUID
pub async fn get_group(groupid: &str) -> Result<AdminViewGroupMsg, GetError> {
    let request = init_request(format!("/v1/group/{}", groupid).as_str());
    let response = match request.send().await {
        Ok(value) => value,
        Err(error) => {
            return Err(GetError {
                err: format!("{:?}", error),
            })
        }
    };
    #[allow(clippy::panic)]
    let data: Entity = match response.json().await {
        Ok(value) => value,
        Err(error) => panic!("Failed to grab the group data into JSON: {:?}", error),
    };
    Ok(AdminViewGroupMsg::Responded { response: data })
}