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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use std::collections::HashMap;
use std::ops::Range;
use std::path::Path;

pub mod chunk_reader;
pub mod component_definitions;
use self::component_definitions::find_component_definitions;
pub mod slotted_positions;
use self::slotted_positions::find_slotted_positions;
pub mod write_tags;
use self::write_tags::{write_until_end_tag, write_until_start_tag, write_until_tag};

// TODO: figure out optimal chunk size
pub const CHUNK_SIZE: usize = 1024;
pub const DEFAULT_SLOT_NAME: &str = "&default";
pub const CONTENT_IN_PROGRESS: usize = 0;

#[derive(Debug, Clone)]
pub struct BuildOptions {
    pub entry_points: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct Tag {
    tag_name: String,
    is_end_tag: bool,
    can_have_content: bool,
    attributes: HashMap<String, String>,
    position: Range<usize>,
}

/// Build the web components from the entry points to an output handler function.
///
/// # Example
///
/// ```rust
/// use wesc::{build, BuildOptions};
///
/// let build_options = BuildOptions {
///    entry_points: vec!["./tests/fixtures/default-slot/index.html".to_string()],
/// };
///
/// build(build_options, &mut |chunk: &[u8]| {
///   println!("{}", String::from_utf8_lossy(chunk));
///   // Write the chunk to a file or stream.
///   // file.write_all(chunk).unwrap();
///   // stream.write_all(chunk).unwrap();
///   // etc.
/// });
/// ```
pub fn build(build_options: BuildOptions, output_handler: &mut impl FnMut(&[u8])) {
    let file_path = &build_options.entry_points[0];

    // Store file indexes that gets increased each time a component of this file is built.
    // Needed for nesting the same component to keep track of the read position.
    let mut file_indexes: HashMap<String, usize> = HashMap::new();
    // The file index together with the file path is used in the key of
    // the positions hashmap to keep track of the read position.
    let mut read_positions: HashMap<String, usize> = HashMap::new();
    // Keep a stack of the component tags that are being built.
    let mut tag_stacks: HashMap<String, Vec<String>> = HashMap::new();
    // Store the definitions of the components.
    // e.g. <link rel="definition" name="w-card" href="./card.html">
    let mut definitions: HashMap<String, HashMap<String, String>> = HashMap::new();
    // Store the parent file path of the component file path.
    let mut parents: HashMap<String, String> = HashMap::new();
    // Store the slotted positions of the light DOM content of the component.
    // There is a default slot and named slots that can have multiple ranges that are out-of-order.
    let mut slotted_positions: HashMap<String, HashMap<String, Vec<Range<usize>>>> = HashMap::new();

    build_file(
        file_path,
        &mut file_indexes,
        &mut read_positions,
        &mut tag_stacks,
        &mut definitions,
        &mut parents,
        &mut slotted_positions,
        output_handler,
    );
}

fn build_file(
    host_file_path: &str,
    file_indexes: &mut HashMap<String, usize>,
    read_positions: &mut HashMap<String, usize>,
    tag_stacks: &mut HashMap<String, Vec<String>>,
    definitions: &mut HashMap<String, HashMap<String, String>>,
    parents: &mut HashMap<String, String>,
    slotted_positions: &mut HashMap<String, HashMap<String, Vec<Range<usize>>>>,
    output_handler: &mut impl FnMut(&[u8]),
) {
    file_indexes.insert(host_file_path.to_string(), 0);
    read_positions.insert(pos_key(0, host_file_path), 0);

    let html_or_template_tag = write_until_start_tag(
        &host_file_path,
        0,
        &vec!["root > html", "root > template"],
        "",
        false,
        &mut |_chunk: &[u8]| {},
    )
    .unwrap();

    let entry_is_component = html_or_template_tag.tag_name == "template";
    let host_pos_key = pos_key(0, &host_file_path);

    if entry_is_component {
        read_positions.insert(host_pos_key.clone(), html_or_template_tag.position.end);
    }

    loop {
        let ended = build_component(
            entry_is_component,
            &host_file_path,
            file_indexes,
            read_positions,
            tag_stacks,
            definitions,
            parents,
            slotted_positions,
            output_handler,
        );

        if ended {
            break;
        }
    }
}

fn pos_key(file_index: usize, file_path: &str) -> String {
    format!("{}:{}", file_index, file_path)
}

fn build_component(
    entry_is_component: bool,
    host_file_path: &str,
    file_indexes: &mut HashMap<String, usize>,
    read_positions: &mut HashMap<String, usize>,
    tag_stacks: &mut HashMap<String, Vec<String>>,
    mut definitions: &mut HashMap<String, HashMap<String, String>>,
    parents: &mut HashMap<String, String>,
    mut slotted_positions: &mut HashMap<String, HashMap<String, Vec<Range<usize>>>>,
    output_handler: &mut impl FnMut(&[u8]),
) -> bool {
    // Find the component definitions in the host file.
    let host_definitions = find_component_definitions(&mut definitions, &host_file_path).unwrap();
    // Put the component definition names in a vector.
    let mut host_definition_names = host_definitions
        .iter()
        .map(|element| element.0.as_str())
        .collect::<Vec<_>>();

    let mut prefix = "";
    let mut until_end_tags = vec![];

    if entry_is_component {
        host_definition_names.push("root > template");
        until_end_tags.push("root > template");
        prefix = "<template>";
    }

    let host_file_index = file_indexes[host_file_path];
    let host_pos_key = pos_key(host_file_index, &host_file_path);

    // Write until after the start tag of a component.
    let component_tag = write_until_tag(
        &host_file_path,
        read_positions[&host_pos_key],
        &host_definition_names,
        &until_end_tags,
        prefix,
        false,
        output_handler,
    );

    let component_tag = match component_tag {
        Ok(tag) => tag,
        Err(_error) => return true,
    };

    if component_tag.tag_name == "template" {
        return true;
    }

    if !component_tag.attributes.contains_key("w-trim") {
        let _ = write_until_start_tag(
            &host_file_path,
            component_tag.position.start,
            &host_definition_names,
            "",
            true,
            output_handler,
        );
    }

    // Save the end position of the start tag of the component.
    read_positions.insert(host_pos_key.clone(), component_tag.position.end);

    // Push the component tag name onto the stack.
    let tag_stack = tag_stacks
        .entry(host_file_path.to_string())
        .or_insert(vec![]);
    tag_stack.push(component_tag.tag_name.clone());

    let component_name = &component_tag.tag_name;

    // Find the file path of the component.
    let component_file_path =
        get_component_file_path(&host_file_path, &host_definitions, component_name).unwrap();

    // Get the file index and increase it by 1 or if it doesn't exist insert 0.
    let component_file_index = *file_indexes
        .entry(component_file_path.to_string())
        .and_modify(|i| *i += 1)
        .or_insert(0);
    let component_pos_key = pos_key(component_file_index, &component_file_path);

    parents.insert(component_file_path.to_string(), host_file_path.to_string());

    let component_definitions =
        find_component_definitions(&mut definitions, &component_file_path).unwrap();
    let component_definition_names = component_definitions
        .iter()
        .map(|element| element.0.as_str())
        .collect::<Vec<_>>();

    let _component_slotted_positions = find_slotted_positions(
        &mut slotted_positions,
        component_tag.position.start,
        &host_file_path,
        &component_name,
        &component_file_index,
        &component_file_path,
    )
    .unwrap();

    // Write until after the start tag of the <template>.
    let template_tag = write_until_start_tag(
        &component_file_path,
        0,
        &vec!["root > template"],
        "",
        false,
        &mut |_chunk: &[u8]| {},
    )
    .unwrap();

    let has_shadowrootmode = template_tag.attributes.contains_key("shadowrootmode");

    let mut component_until_start_tags = component_definition_names.clone();
    component_until_start_tags.push("root > template");

    if has_shadowrootmode {
        output_handler(b"\n");
        write_until_start_tag(
            &component_file_path,
            0,
            &vec!["root > template"],
            "",
            true,
            output_handler,
        )
        .unwrap();
    } else {
        component_until_start_tags.push("slot");
    }

    // Save the end position of the start tag of the template.
    read_positions.insert(component_pos_key.clone(), template_tag.position.end);

    loop {
        let tag = write_until_tag(
            &component_file_path,
            read_positions[&component_pos_key],
            &component_until_start_tags,
            &vec!["root > template"],
            "<template>",
            false,
            output_handler,
        );

        let tag = match tag {
            Ok(tag) => tag,
            Err(_error) => break false,
        };

        read_positions.insert(component_pos_key.clone(), tag.position.end);

        if tag.tag_name == "template" && tag.is_end_tag {
            if has_shadowrootmode {
                output_handler(b"</template>\n");
            }

            // If there is no default slot, skip slotted content.
            if let Ok(component_end_tag) = write_until_end_tag(
                &host_file_path,
                read_positions[&host_pos_key],
                &host_definition_names,
                format!("<{}>", component_tag.tag_name).as_str(),
                false,
                &mut |_chunk: &[u8]| {},
            ) {
                // Pop the component tag name off the stack.
                let tag_stack = tag_stacks
                    .entry(host_file_path.to_string())
                    .or_insert(vec![]);
                tag_stack.pop();

                // Decrease file index by 1 if the component ends.
                if let Some(value) = file_indexes.get_mut(&component_file_path.to_string()) {
                    if *value > 0 {
                        *value -= 1;
                    }
                }

                if !component_tag.attributes.contains_key("w-trim") {
                    output_handler(format!("</{}>", component_tag.tag_name).as_bytes());
                }

                read_positions.insert(host_pos_key, component_end_tag.position.end);
            }

            break false;
        }

        if component_definition_names.contains(&tag.tag_name.as_str()) {
            read_positions.insert(component_pos_key.clone(), tag.position.start);

            build_component(
                entry_is_component,
                &component_file_path,
                file_indexes,
                read_positions,
                tag_stacks,
                definitions,
                parents,
                slotted_positions,
                output_handler,
            );

            continue;
        }

        if tag.tag_name == "slot" {
            let host_start_pos = read_positions[&host_pos_key];
            let slot_name = tag.attributes.get("name");

            loop {
                if let Some(light_tag) = build_component_content(
                    entry_is_component,
                    slot_name,
                    &host_file_path,
                    file_indexes,
                    read_positions,
                    tag_stacks,
                    definitions,
                    parents,
                    slotted_positions,
                    output_handler,
                ) {
                    if light_tag.is_end_tag && light_tag.tag_name == component_tag.tag_name {
                        break;
                    }
                } else {
                    break;
                }
            }

            // Output the fallback slot content if there is no slotted content.
            if let Ok(end_slot_tag) = write_until_end_tag(
                &component_file_path,
                read_positions[&component_pos_key],
                &vec!["slot"],
                "<slot>",
                false,
                &mut |chunk: &[u8]| {
                    if host_start_pos == read_positions[&host_pos_key] {
                        output_handler(chunk);
                    }
                },
            ) {
                read_positions.insert(component_pos_key.clone(), end_slot_tag.position.end);
            }
        }
    }
}

fn build_component_content(
    entry_is_component: bool,
    slot_name_option: Option<&String>,
    host_file_path: &str,
    file_indexes: &mut HashMap<String, usize>,
    read_positions: &mut HashMap<String, usize>,
    tag_stacks: &mut HashMap<String, Vec<String>>,
    mut definitions: &mut HashMap<String, HashMap<String, String>>,
    parents: &mut HashMap<String, String>,
    slotted_positions: &mut HashMap<String, HashMap<String, Vec<Range<usize>>>>,
    output_handler: &mut impl FnMut(&[u8]),
) -> Option<Tag> {
    let host_definitions = find_component_definitions(&mut definitions, &host_file_path).unwrap();
    let host_definition_names = host_definitions
        .iter()
        .map(|element| element.0.as_str())
        .collect::<Vec<_>>();

    let mut host_until_start_tags = host_definition_names.clone();
    host_until_start_tags.push("slot");
    host_until_start_tags.push("*[slot]");

    // Get the component tag name from the stack.
    let tag_stack = tag_stacks
        .entry(host_file_path.to_string())
        .or_insert(vec![]);
    let current_tag = tag_stack.last().unwrap().as_str();

    let host_pos_key = pos_key(file_indexes[host_file_path], &host_file_path);
    let component_slotted_positions = slotted_positions.get_mut(&host_pos_key).unwrap();

    let slot_name = match slot_name_option {
        Some(name) => name,
        None => DEFAULT_SLOT_NAME,
    };

    let slotted_ranges = component_slotted_positions.get_mut(slot_name).unwrap();
    let slotted_range = match slotted_ranges.first() {
        Some(range) => range,
        None => return None,
    };

    if slotted_range.start != CONTENT_IN_PROGRESS {
        read_positions.insert(host_pos_key.clone(), slotted_range.start);
        slotted_ranges[0].start = CONTENT_IN_PROGRESS;
    }

    if let Ok(light_tag) = write_until_tag(
        &host_file_path,
        read_positions[&host_pos_key],
        &host_until_start_tags,
        &host_definition_names,
        format!("<{}>", current_tag).as_str(),
        false,
        &mut |chunk: &[u8]| {
            if slot_name_option.is_none() {
                output_handler(chunk);
            }
        },
    ) {
        if light_tag.tag_name == "slot" {
            if let None = light_tag.attributes.get("name") {
                read_positions.insert(host_pos_key.clone(), light_tag.position.end);

                let parents_clone = parents.clone();
                let parent_file_path = parents_clone[host_file_path].as_str();

                // slotted_ranges.remove(0);

                let light_tag = build_component_content(
                    entry_is_component,
                    slot_name_option,
                    &parent_file_path,
                    file_indexes,
                    read_positions,
                    tag_stacks,
                    definitions,
                    parents,
                    slotted_positions,
                    output_handler,
                );

                // Output the fallback slot content if there is no slotted content.
                if let Ok(end_slot_tag) = write_until_end_tag(
                    &host_file_path,
                    read_positions[&host_pos_key],
                    &vec!["slot"],
                    "<slot>",
                    false,
                    &mut |_chunk: &[u8]| {
                        // TODO: find out when to output the fallback content.
                        // if host_start_pos == read_positions[&host_pos_key] {
                        //     output_handler(chunk);
                        // }
                    },
                ) {
                    read_positions.insert(host_pos_key.clone(), end_slot_tag.position.end);
                }

                return light_tag;
            }
        }

        if !light_tag.is_end_tag {
            read_positions.insert(host_pos_key.clone(), light_tag.position.start);

            // Handle named slotted elements. e.g. <h3 slot="title">Title</h3>
            if let Some(slot_name) = light_tag.attributes.get("slot") {
                if slot_name_option.is_some() && slot_name_option.unwrap() == slot_name {
                    read_positions.insert(host_pos_key.clone(), light_tag.position.start);

                    let _ = write_until_start_tag(
                        &host_file_path,
                        read_positions[&host_pos_key],
                        &vec![light_tag.tag_name.as_str()],
                        "",
                        true,
                        output_handler,
                    );

                    read_positions.insert(host_pos_key.clone(), light_tag.position.end);

                    if light_tag.can_have_content {
                        if let Ok(mut end_slot_tag) = write_until_end_tag(
                            &host_file_path,
                            read_positions[&host_pos_key],
                            &vec![light_tag.tag_name.as_str()],
                            format!("<{}>", light_tag.tag_name).as_str(),
                            true,
                            &mut |chunk: &[u8]| {
                                output_handler(chunk);
                            },
                        ) {
                            read_positions.insert(host_pos_key.clone(), end_slot_tag.position.end);

                            end_slot_tag
                                .attributes
                                .insert("slot".to_string(), slot_name.clone());

                            slotted_ranges.remove(0);
                            return Some(end_slot_tag);
                        }
                    }

                    slotted_ranges.remove(0);
                    return Some(light_tag);
                }

                // Ignore light tags with a slot attribute that doesn't match the slot name.
                read_positions.insert(host_pos_key.clone(), light_tag.position.end);

                if let Ok(mut end_slot_tag) = write_until_end_tag(
                    &host_file_path,
                    read_positions[&host_pos_key],
                    &vec![light_tag.tag_name.as_str()],
                    format!("<{}>", light_tag.tag_name).as_str(),
                    false,
                    &mut |_chunk: &[u8]| {
                        // TODO: find out when to output the fallback content.
                        // if host_start_pos == read_positions[&host_pos_key] {
                        //     output_handler(chunk);
                        // }
                    },
                ) {
                    read_positions.insert(host_pos_key.clone(), end_slot_tag.position.end);

                    end_slot_tag
                        .attributes
                        .insert("slot".to_string(), slot_name.clone());

                    slotted_ranges.remove(0);
                    return Some(end_slot_tag);
                }
            } else {
                read_positions.insert(host_pos_key.clone(), light_tag.position.start);

                build_component(
                    entry_is_component,
                    &host_file_path,
                    file_indexes,
                    read_positions,
                    tag_stacks,
                    definitions,
                    parents,
                    slotted_positions,
                    output_handler,
                );
            }

            return Some(light_tag);
        }

        if light_tag.is_end_tag {
            read_positions.insert(host_pos_key.clone(), light_tag.position.start);
        }

        return Some(light_tag);
    }

    return None;
}

fn get_component_file_path(
    file_path: &str,
    defs: &HashMap<String, String>,
    name: &str,
) -> Option<String> {
    let dir = Path::new(&file_path).parent().unwrap();
    let component_href = defs[name].as_str();
    let component_href = Path::new(component_href);
    let component_file_path = dir.join(&component_href);
    component_file_path.to_string_lossy().to_string().into()
}