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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! GUI code related to ligation operations.

use std::{collections::HashMap, path::PathBuf};

use eframe::{
    egui::{
        Align2, Color32, FontFamily, FontId, Frame, Pos2, Rect, RichText, ScrollArea, Sense, Shape,
        Stroke, Ui, pos2, vec2,
    },
    emath::RectTransform,
};
use lin_alg::map_linear;
use na_seq::{
    ligation,
    ligation::{LigationFragment, digest},
    seq_to_str_lower,
};

use crate::{
    gui::{
        BACKGROUND_COLOR, COL_SPACING, ROW_SPACING,
        circle::{FEATURE_OUTLINE_COLOR, FEATURE_STROKE_WIDTH},
        lin_maps::seq_lin_disp,
        navigation::{Tab, get_tab_names, name_from_path},
        select_color_text,
        theme::COLOR_ACTION,
    },
    state::State,
    util::filter_res,
};

// This X offset must have room for the RE Nts displayed on the left.
const OFFSET_X: f32 = 60.;
const OFFSET_Y: f32 = 30.;

const PRODUCT_ROW_SPACING: f32 = 60.;
const FRAG_DISP_HEIGHT: f32 = 30.;
const FRAG_DISP_HEIGHT_DIV2: f32 = FRAG_DISP_HEIGHT / 2.;

// We cycle through this for visual separation
const SEQ_COLORS: [Color32; 4] = [
    Color32::LIGHT_RED,
    Color32::LIGHT_GREEN,
    Color32::LIGHT_YELLOW,
    Color32::LIGHT_GRAY,
];

/// Draw a graphical depiction of digestion products.
fn draw_graphics(products: &[LigationFragment], seq_len: usize, ui: &mut Ui) {
    Frame::canvas(ui.style())
        .fill(BACKGROUND_COLOR)
        .show(ui, |ui| {
            let (response, _painter) = {
                let desired_size = vec2(ui.available_width(), ui.available_height());
                ui.allocate_painter(desired_size, Sense::click())
            };

            let to_screen = RectTransform::from_to(
                // Rect::from_min_size(pos2(0., -VERITICAL_CIRCLE_OFFSET), response.rect.size()),
                Rect::from_min_size(Pos2::ZERO, response.rect.size()),
                response.rect,
            );

            // let rect_size = response.rect.size();

            let mut shapes = Vec::new();

            let stroke = Stroke::new(FEATURE_STROKE_WIDTH, FEATURE_OUTLINE_COLOR);

            let mut row_px = OFFSET_Y;

            // Scale pixel length based on the full sequence length.
            let left_edge_px = OFFSET_X;
            // Leave enough room on both sides for descriptive text annotations.
            let right_edge_px = ui.available_width() - OFFSET_X - 80.;

            let mut seq_colors: HashMap<String, Color32> = HashMap::new();
            let mut color_i = 0;

            for frag in products {
                let frag_color = if seq_colors.contains_key(&frag.source_name) {
                    seq_colors[&frag.source_name]
                } else {
                    color_i = (color_i + 1) % SEQ_COLORS.len();
                    seq_colors.insert(frag.source_name.to_owned(), SEQ_COLORS[color_i]);
                    SEQ_COLORS[color_i]
                };

                let start_x = OFFSET_X;
                // let end_x = start_x + frag.seq.len() as f32 * 2.; // todo: Rough.

                // todo: This approach won't work when adding in fragments from other sequences.
                let end_x = map_linear(
                    frag.seq.len() as f32,
                    (0., seq_len as f32),
                    (left_edge_px, right_edge_px),
                );

                shapes.push(Shape::convex_polygon(
                    vec![
                        to_screen * pos2(start_x, row_px - FRAG_DISP_HEIGHT_DIV2),
                        to_screen * pos2(end_x, row_px - FRAG_DISP_HEIGHT_DIV2),
                        to_screen * pos2(end_x, row_px + FRAG_DISP_HEIGHT_DIV2),
                        to_screen * pos2(start_x, row_px + FRAG_DISP_HEIGHT_DIV2),
                    ],
                    frag_color,
                    stroke,
                ));

                let box_center = pos2((end_x + start_x) / 2., row_px);

                // Draw the RE ends.
                let label_pt_left_top = pos2(start_x - 10., row_px - 10.);
                let label_pt_right_top = pos2(end_x + 10., row_px - 10.);

                let label_pt_left_bottom = pos2(start_x - 10., row_px + 10.);
                let label_pt_right_bottom = pos2(end_x + 10., row_px + 10.);

                let (re_text_left_top, re_text_left_bottom, re_name_left) = match &frag.re_left {
                    Some(re) => (
                        seq_to_str_lower(&re.overhang_top_left(&[])), // todo: Update this
                        seq_to_str_lower(&re.overhang_bottom_left(&[])), // todo: Update this
                        re.name.clone(),
                    ),
                    None => (String::new(), String::new(), String::new()),
                };

                let (re_text_right_top, re_text_right_bottom, re_name_right) = match &frag.re_right
                {
                    Some(re) => (
                        seq_to_str_lower(&re.overhang_top_right(&[])), // todo: Update this
                        seq_to_str_lower(&re.overhang_bottom_right(&[])), // todo: Update this
                        re.name.clone(),
                    ),
                    None => (String::new(), String::new(), String::new()),
                };

                // todo: Allow viewing and copying fragment seqs, eg from selecting them.

                // Draw info like fragment length inside the boxes.
                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        to_screen * box_center,
                        Align2::CENTER_CENTER,
                        &format!("{} bp", frag.seq.len()),
                        FontId::new(14., FontFamily::Proportional),
                        Color32::BLACK,
                    )
                }));

                // Left, top
                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        to_screen * label_pt_left_top,
                        Align2::RIGHT_CENTER,
                        &re_text_left_top,
                        FontId::new(14., FontFamily::Proportional),
                        Color32::LIGHT_YELLOW,
                    )
                }));

                // Right, top
                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        to_screen * label_pt_right_top,
                        Align2::LEFT_CENTER,
                        &re_text_right_top,
                        FontId::new(14., FontFamily::Proportional),
                        Color32::LIGHT_YELLOW,
                    )
                }));

                // Left, bottom
                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        to_screen * label_pt_left_bottom,
                        Align2::RIGHT_CENTER,
                        &re_text_left_bottom,
                        FontId::new(14., FontFamily::Proportional),
                        Color32::LIGHT_YELLOW,
                    )
                }));

                // Right, bottom
                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        to_screen * label_pt_right_bottom,
                        Align2::LEFT_CENTER,
                        &re_text_right_bottom,
                        FontId::new(14., FontFamily::Proportional),
                        Color32::LIGHT_YELLOW,
                    )
                }));

                // Text description of which enzymes were used.
                let enzyme_text = format!("{}  |  {}", re_name_left, re_name_right);
                let enzyme_text_pos = to_screen * pos2(end_x + 50., row_px);
                let source_name_text_pos = to_screen * pos2(end_x + 150., row_px);

                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        enzyme_text_pos,
                        Align2::LEFT_CENTER,
                        &enzyme_text,
                        FontId::new(14., FontFamily::Proportional),
                        Color32::LIGHT_RED,
                    )
                }));

                // Show the source name this fragment came from.

                shapes.push(ui.ctx().fonts(|fonts| {
                    Shape::text(
                        fonts,
                        source_name_text_pos,
                        Align2::LEFT_CENTER,
                        &frag.source_name,
                        FontId::new(14., FontFamily::Proportional),
                        frag_color,
                    )
                }));

                row_px += PRODUCT_ROW_SPACING;
            }

            ui.painter().extend(shapes);
        });
}

fn tab_selection(
    tabs: &mut Vec<usize>,
    path_loaded: &[Tab],
    plasmid_names: &[&str],
    ui: &mut Ui,
) -> bool {
    let mut clear_res = false;

    ui.horizontal(|ui| {
        ui.heading("Opened files to digest");
        ui.add_space(COL_SPACING);

        for (name, i) in get_tab_names(path_loaded, plasmid_names, true) {
            // todo: DRY with page selectors and Cloning.
            let selected = tabs.contains(&i);

            let button = ui.button(
                select_color_text(&name, selected), // .background_color(TAB_BUTTON_COLOR),
            );

            if button.clicked() {
                if tabs.contains(&i) {
                    // todo: DRY with res_selected below.
                    for (j, tab_i) in tabs.iter().enumerate() {
                        if i == *tab_i {
                            tabs.remove(j);
                            // This is crude; we only need to re-select REs that were enabled by this tab.
                            clear_res = true;
                            break;
                        }
                    }
                } else {
                    tabs.push(i);
                }
            }

            ui.add_space(COL_SPACING / 2.);
        }
    });
    clear_res
}

// // todo
// /// Remove selected res if they are filtered out.
// fn filter_res_selected(data: &mut ReUi, lib: &[RestrictionEnzyme]) {
//     for name in &mut data.res_selected {
//         let mut re = None;
//         for re_ in lib {
//             // if &re_.name == name {
//             if &re_.name == name {
//                 re = Some(re_.clone());
//                 break;
//             }
//             if re.is_none() {
//                 eprintln!("Error: Unable to find matching RE");
//                 break;
//             }
//         }
//
//         let re = re.unwrap();
//     }
// }

pub fn ligation_page(state: &mut State, ui: &mut Ui) {
    // todo: Scrolling is not working
    ScrollArea::vertical().id_salt(100).show(ui, |ui| {
        // todo: Cache calcs in this fn A/R
        // Adjust the nucleotide width of digest bars based on the longest sequence selected.
        let mut longest_seq = 0;
        for active in &state.ui.re.tabs_selected {
            if state.generic[*active].seq.len() > longest_seq {
                longest_seq = state.generic[*active].seq.len();
            }
        }

        // todo: Don't run this every frame! Store in state, and update it only when something notable changes.
        let res_matched = filter_res(&state.ui.re, &state.volatile, &state.restriction_enzyme_lib);

        ui.horizontal(|ui| {
            ui.heading("Digestion and ligation");
            ui.add_space(COL_SPACING * 2.);

            let mut changed_filters = false;

            ui.label("Unique cutters only:").on_hover_text("Only display restriction enzymes that cut a sequence exactly once. (Affects display on other pages as well).");
            if ui.checkbox(&mut state.ui.re.unique_cutters_only, "").changed() {
                changed_filters = true;
            };

            ui.add_space(COL_SPACING);

            ui.label("Sticky ends only:").on_hover_text("Only display restriction enzymes that produce overhangs (sticky ends). Don't show ones that produce blunt ends. (Affects display on other pages as well).");
            if ui.checkbox(&mut state.ui.re.sticky_ends_only, "").changed() {
                changed_filters = true;
            };

            ui.add_space(COL_SPACING);

            ui.label("2+ sequences only:");
            if ui.checkbox(&mut state.ui.re.multiple_seqs, "")
                .on_hover_text("Only display restriction enzymes that cut two or more selected sequences, if applicable.")
                .changed() {
                changed_filters = true;
            };

            ui.add_space(COL_SPACING);

            // If we've c fmt
            // hanged filters, update REs selected IRT these filtersx.
            if changed_filters {
                // filter_res_selected(&mut state.ui.re, &state.restriction_enzyme_lib);
            }

        });
        ui.add_space(ROW_SPACING);

        let plasmid_names: &Vec<_> = &state.generic.iter().map(|v| v.metadata.plasmid_name.as_str()).collect();

        let clear_res = tab_selection(&mut state.ui.re.tabs_selected, &state.tabs_open, plasmid_names, ui);
        if clear_res {
            state.ui.re.res_selected = Vec::new();
        }

        ui.add_space(ROW_SPACING / 2.);

        // // todo: This is potentially un-ideal computationally. Note that the name-based code is stored permanently.
        // // todo: NOte that this is just for the highlights. todo: Just store teh whole Re Match instead of names as state.ui.res_selected.
        // let mut res_sel = Vec::new();
        // for name in &state.ui.re.res_selected {
        //     for re in &state.restriction_enzyme_lib {
        //         if name == &re.name {
        //             res_sel.push(re);
        //         }
        //     }
        // }

        for active in &state.ui.re.tabs_selected {
            seq_lin_disp(&state.generic[*active], true, state.ui.selected_item, &state.ui.re.res_selected, None, &state.ui,&state.volatile[state.active].restriction_enzyme_matches,
                         &state.restriction_enzyme_lib, ui);
            ui.add_space(ROW_SPACING/2.);
        }

        // todo: Highlight common (and later, compatible) RE matches among fragments.

        ui.horizontal(|ui| {
            ui.heading("Restriction enzymes matched");
            ui.add_space(COL_SPACING);

            ui.label("Click to select for digestion.");
        });

        let res_per_row = 8; // todo: Based on screen width etc.
        let num_re_rows = res_matched.len() / res_per_row + 1;

        for row_i in 0..num_re_rows {
            ui.horizontal(|ui| {
                for col_i in 0..res_per_row {
                    let index = row_i * res_per_row + col_i;
                    if index + 1 > res_matched.len() {
                        break;
                    }
                    let re = res_matched[index];

                    let selected = state.ui.re.res_selected.contains(&re);

                    if ui.button(select_color_text(&re.name, selected)).clicked() {
                        if selected {
                            for (i, re_sel) in state.ui.re.res_selected.iter().enumerate() {
                                if re_sel == re {
                                    state.ui.re.res_selected.remove(i);
                                    break;
                                }
                            }
                        } else {
                            state.ui.re.res_selected.push(re.clone());
                        }
                    }
                    ui.label(re.cut_depiction());
                    ui.add_space(COL_SPACING / 2.);
                }
                ui.add_space(COL_SPACING);
            });
        }

        ui.add_space(ROW_SPACING);

        ui.horizontal(|ui| {
            if !state.ui.re.res_selected.is_empty() {
                if ui
                    .button(RichText::new("Digest").color(COLOR_ACTION))
                    .clicked()
                {
                    let mut products = Vec::new();

                    for active in &state.ui.re.tabs_selected {
                        let source_name = name_from_path(
                            &state.tabs_open[*active].path,
                            &state.generic[*active].metadata.plasmid_name,
                            true,
                        );
                        products.extend(digest(
                            &source_name,
                            &state.ui.re.res_selected,
                            &state.volatile[*active].restriction_enzyme_matches,
                            &state.restriction_enzyme_lib,
                            &state.generic[*active].seq,
                            state.generic[*active].topology,
                        ));
                    }

                    state.volatile[state.active].re_digestion_products = products;
                }
            }

            if !state.volatile[state.active]
                .re_digestion_products
                .is_empty()
            {
                // todo: Put back when ready
                // ui.add_space(COL_SPACING);
                // if ui
                //     .button(RichText::new("Ligate").color(COLOR_ACTION))
                //     .clicked()
                // {
                //     // state.volatile[state.active].re_ligation_products = ligate(
                //     //     &state.volatile[state.active].re_digestion_products,
                //     // );
                // }
            }
        });

        // Display the digestion products,
        draw_graphics(
            &state.volatile[state.active].re_digestion_products,
            longest_seq,
            ui,
        );
    });
}