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
use crate::actions::GeneralArgs;
use crate::render::ui::{fuzzy_select_with_key, multi_fuzzy_select_with_key};
use crate::types::context::BergContext;
use crate::types::git::OwnerRepo;
use anyhow::Context;
use forgejo_api::structs::{CreateIssueOption, IssueGetMilestonesListQuery, IssueListLabelsQuery};
use strum::*;

use crate::actions::text_manipulation::{edit_prompt_for, input_prompt_for, select_prompt_for};

use clap::Parser;

/// Create an issue
#[derive(Parser, Debug)]
pub struct CreateIssueArgs {
    /// Title or summary
    #[arg(short, long)]
    pub title: Option<String>,

    /// Comma-delimited list of label ids
    #[arg(short, long, value_name = "LABEL,...", value_delimiter = ',')]
    pub labels: Option<Vec<String>>,

    /// Main description of issue
    #[arg(id = "description", short, long)]
    pub body: Option<String>,

    /// Comma-delimited list of assignee names
    #[arg(short, long, value_name = "ASSIGNEE,...", value_delimiter = ',')]
    pub assignees: Option<Vec<String>>,

    /// Name of the milestone the issue is related to
    #[arg(short, long)]
    pub milestone: Option<String>,
}

#[derive(Display, PartialEq, Eq, VariantArray)]
enum CreatableFields {
    Labels,
    Assignees,
    Milestone,
}

impl CreateIssueArgs {
    pub async fn run(self, general_args: GeneralArgs) -> anyhow::Result<()> {
        let _ = general_args;
        let ctx = BergContext::new(self).await?;
        let OwnerRepo { repo, owner } = ctx.owner_repo()?;
        let options = create_options(&ctx).await?;
        tracing::debug!("{options:?}");
        let issue = ctx
            .client
            .issue_create_issue(owner.as_str(), repo.as_str(), options)
            .await?;
        tracing::debug!("{issue:?}");
        Ok(())
    }
}

async fn create_options(ctx: &BergContext<CreateIssueArgs>) -> anyhow::Result<CreateIssueOption> {
    let title = match ctx.args.title.as_ref().cloned() {
        Some(title) => title,
        None => inquire::Text::new(input_prompt_for("Issue Title").as_str()).prompt()?,
    };

    let mut options = CreateIssueOption {
        title,
        assignee: None,
        assignees: None,
        body: None,
        closed: None,
        due_date: None,
        labels: None,
        milestone: None,
        r#ref: None,
    };

    let optional_data = {
        use CreatableFields::*;
        [
            (Labels, ctx.args.labels.is_none()),
            (Assignees, ctx.args.assignees.is_none()),
            (Milestone, ctx.args.milestone.is_none()),
        ]
        .into_iter()
        .filter_map(|(name, missing)| missing.then_some(name))
        .collect::<Vec<_>>()
    };

    let chosen_optionals = multi_fuzzy_select_with_key(
        &optional_data,
        "Choose optional properties",
        |_| false,
        |o| o.to_string(),
    )?;

    options.body.replace(issue_body(ctx)?);
    {
        use CreatableFields::*;
        options.labels = issue_labels(ctx, chosen_optionals.contains(&&Labels)).await?;
        options.assignees = issue_assignees(ctx, chosen_optionals.contains(&&Assignees)).await?;
        options.milestone = issue_milestone(ctx, chosen_optionals.contains(&&Milestone)).await?;
    }

    Ok(options)
}

fn issue_body(ctx: &BergContext<CreateIssueArgs>) -> anyhow::Result<String> {
    let body = match ctx.args.body.as_ref() {
        Some(body) => body.clone(),
        None => inquire::Editor::new(edit_prompt_for("a description").as_str())
            .with_predefined_text("Enter a issue description")
            .prompt()?,
    };
    Ok(body)
}

async fn issue_labels(
    ctx: &BergContext<CreateIssueArgs>,
    interactive: bool,
) -> anyhow::Result<Option<Vec<u64>>> {
    let OwnerRepo { repo, owner } = ctx.owner_repo()?;

    let all_labels = ctx
        .client
        .issue_list_labels(
            owner.as_str(),
            repo.as_str(),
            IssueListLabelsQuery::default(),
        )
        .await?;

    let labels = match &ctx.args.labels {
        Some(label_names) => {
            let label_ids = all_labels
                .iter()
                .filter(|l| {
                    l.name
                        .as_ref()
                        .is_some_and(|name| label_names.contains(name))
                })
                .filter_map(|l| l.id)
                .collect::<Vec<_>>();
            Some(label_ids)
        }
        None => {
            if !interactive {
                return Ok(None);
            }

            let selected_labels = multi_fuzzy_select_with_key(
                &all_labels,
                select_prompt_for("labels"),
                |_| false,
                |l| {
                    l.name
                        .as_ref()
                        .cloned()
                        .unwrap_or_else(|| String::from("???"))
                },
            )?;

            let label_ids = selected_labels
                .iter()
                .filter_map(|l| l.id)
                .collect::<Vec<_>>();

            Some(label_ids)
        }
    };
    Ok(labels)
}

async fn issue_assignees(
    ctx: &BergContext<CreateIssueArgs>,
    interactive: bool,
) -> anyhow::Result<Option<Vec<String>>> {
    let OwnerRepo { repo, owner } = ctx.owner_repo()?;

    let all_assignees = ctx
        .client
        .repo_get_assignees(owner.as_str(), repo.as_str())
        .await?;
    let assignees = match &ctx.args.assignees {
        Some(assignees_names) => Some(assignees_names.clone()),
        None => {
            tracing::debug!("Hey");
            if !interactive {
                return Ok(None);
            }

            let selected_assignees = multi_fuzzy_select_with_key(
                &all_assignees,
                select_prompt_for("assignees"),
                |_| false,
                |u| {
                    u.login
                        .as_ref()
                        .cloned()
                        .unwrap_or_else(|| String::from("???"))
                },
            )?;

            Some(
                selected_assignees
                    .into_iter()
                    .filter_map(|u| u.login.as_ref().cloned())
                    .collect::<Vec<_>>(),
            )
        }
    };

    Ok(assignees)
}

async fn issue_milestone(
    ctx: &BergContext<CreateIssueArgs>,
    interactive: bool,
) -> anyhow::Result<Option<u64>> {
    let OwnerRepo { repo, owner } = ctx.owner_repo()?;

    let all_milestones = ctx
        .client
        .issue_get_milestones_list(
            owner.as_str(),
            repo.as_str(),
            IssueGetMilestonesListQuery::default(),
        )
        .await?;

    let milestone = match &ctx.args.milestone {
        Some(milestone_name) => Some(
            all_milestones
                .iter()
                .find(|m| m.title.as_ref().is_some_and(|name| name == milestone_name))
                .and_then(|milestone| milestone.id)
                .context(format!(
                    "Milestone with name {milestone_name} wasn't found. Check the spelling"
                ))?,
        ),
        None => {
            if !interactive {
                return Ok(None);
            }
            let selected_milestone =
                fuzzy_select_with_key(&all_milestones, select_prompt_for("milestones"), |m| {
                    m.title
                        .as_ref()
                        .cloned()
                        .unwrap_or_else(|| String::from("???"))
                })?;

            Some(
                selected_milestone
                    .id
                    .context("Selected milestone's id is missing")?,
            )
        }
    };

    Ok(milestone)
}