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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! Types for kcl project and modeling-app settings.

pub mod file;
pub mod project;

use anyhow::Result;
use parse_display::{Display, FromStr};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use validator::{Validate, ValidateRange};

const DEFAULT_THEME_COLOR: f64 = 264.5;
pub const DEFAULT_PROJECT_KCL_FILE: &str = "main.kcl";
const DEFAULT_PROJECT_NAME_TEMPLATE: &str = "project-$nnn";

/// High level configuration.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct Configuration {
    /// The settings for the modeling app.
    #[serde(default, skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub settings: Settings,
}

impl Configuration {
    // TODO: remove this when we remove backwards compatibility with the old settings file.
    pub fn backwards_compatible_toml_parse(toml_str: &str) -> Result<Self> {
        let mut settings = toml::from_str::<Self>(toml_str)?;

        if let Some(project_directory) = &settings.settings.app.project_directory {
            if settings.settings.project.directory.to_string_lossy().is_empty() {
                settings.settings.project.directory.clone_from(project_directory);
                settings.settings.app.project_directory = None;
            }
        }

        if let Some(theme) = &settings.settings.app.theme {
            if settings.settings.app.appearance.theme == AppTheme::default() {
                settings.settings.app.appearance.theme = *theme;
                settings.settings.app.theme = None;
            }
        }

        if let Some(theme_color) = &settings.settings.app.theme_color {
            if settings.settings.app.appearance.color == AppColor::default() {
                settings.settings.app.appearance.color = theme_color.clone().into();
                settings.settings.app.theme_color = None;
            }
        }

        if let Some(enable_ssao) = settings.settings.app.enable_ssao {
            if settings.settings.modeling.enable_ssao.into() {
                settings.settings.modeling.enable_ssao = enable_ssao.into();
                settings.settings.app.enable_ssao = None;
            }
        }

        settings.validate()?;

        Ok(settings)
    }

    #[cfg(not(target_arch = "wasm32"))]
    /// Initialize the project directory.
    pub async fn ensure_project_directory_exists(&self) -> Result<std::path::PathBuf> {
        let project_dir = &self.settings.project.directory;

        // Check if the directory exists.
        if !project_dir.exists() {
            // Create the directory.
            tokio::fs::create_dir_all(project_dir).await?;
        }

        Ok(project_dir.clone())
    }

    #[cfg(not(target_arch = "wasm32"))]
    /// Create a new project directory.
    pub async fn create_new_project_directory(
        &self,
        project_name: &str,
        initial_code: Option<&str>,
    ) -> Result<crate::settings::types::file::Project> {
        let main_dir = &self.ensure_project_directory_exists().await?;

        if project_name.is_empty() {
            return Err(anyhow::anyhow!("Project name cannot be empty."));
        }

        // Create the project directory.
        let project_dir = main_dir.join(project_name);

        // Create the directory.
        if !project_dir.exists() {
            tokio::fs::create_dir_all(&project_dir).await?;
        }

        // Write the initial project file.
        let project_file = project_dir.join(DEFAULT_PROJECT_KCL_FILE);
        tokio::fs::write(&project_file, initial_code.unwrap_or_default()).await?;

        Ok(crate::settings::types::file::Project {
            file: crate::settings::types::file::FileEntry {
                path: project_dir.to_string_lossy().to_string(),
                name: project_name.to_string(),
                // We don't need to recursively get all files in the project directory.
                // Because we just created it and it's empty.
                children: None,
            },
            default_file: project_file.to_string_lossy().to_string(),
            metadata: Some(tokio::fs::metadata(&project_dir).await?.into()),
            kcl_file_count: 1,
            directory_count: 0,
        })
    }

    #[cfg(not(target_arch = "wasm32"))]
    /// List all the projects for the configuration.
    pub async fn list_projects(&self) -> Result<Vec<crate::settings::types::file::Project>> {
        // Get all the top level directories in the project directory.
        let main_dir = &self.ensure_project_directory_exists().await?;
        let mut projects = vec![];

        let mut entries = tokio::fs::read_dir(main_dir).await?;
        while let Some(e) = entries.next_entry().await? {
            if !e.file_type().await?.is_dir() || e.file_name().to_string_lossy().starts_with('.') {
                // We don't care it's not a directory
                // or it's a hidden directory.
                continue;
            }

            // Make sure the project has at least one kcl file in it.
            let project = self.get_project_info(&e.path().display().to_string()).await?;
            if project.kcl_file_count == 0 {
                continue;
            }

            projects.push(project);
        }

        Ok(projects)
    }

    #[cfg(not(target_arch = "wasm32"))]
    /// Get information about a project.
    pub async fn get_project_info(&self, project_path: &str) -> Result<crate::settings::types::file::Project> {
        // Check the directory.
        let project_dir = std::path::Path::new(project_path);
        if !project_dir.exists() {
            return Err(anyhow::anyhow!("Project directory does not exist: {}", project_path));
        }

        // Make sure it is a directory.
        if !project_dir.is_dir() {
            return Err(anyhow::anyhow!("Project path is not a directory: {}", project_path));
        }

        let walked = crate::settings::utils::walk_dir(project_dir).await?;

        let mut project = crate::settings::types::file::Project {
            file: walked.clone(),
            metadata: Some(tokio::fs::metadata(&project_dir).await?.into()),
            kcl_file_count: 0,
            directory_count: 0,
            default_file: crate::settings::types::file::get_default_kcl_file_for_dir(project_dir, walked).await?,
        };

        // Populate the number of KCL files in the project.
        project.populate_kcl_file_count()?;

        //Populate the number of directories in the project.
        project.populate_directory_count()?;

        Ok(project)
    }
}

/// High level settings.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct Settings {
    /// The settings for the modeling app.
    #[serde(default, skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub app: AppSettings,
    /// Settings that affect the behavior while modeling.
    #[serde(default, skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub modeling: ModelingSettings,
    /// Settings that affect the behavior of the KCL text editor.
    #[serde(default, alias = "textEditor", skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub text_editor: TextEditorSettings,
    /// Settings that affect the behavior of project management.
    #[serde(default, alias = "projects", skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub project: ProjectSettings,
    /// Settings that affect the behavior of the command bar.
    #[serde(default, alias = "commandBar", skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub command_bar: CommandBarSettings,
}

/// Application wide settings.
// TODO: When we remove backwards compatibility with the old settings file, we can remove the
// aliases to camelCase (and projects plural) from everywhere.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct AppSettings {
    /// The settings for the appearance of the app.
    #[serde(default, skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub appearance: AppearanceSettings,
    /// The onboarding status of the app.
    #[serde(default, alias = "onboardingStatus", skip_serializing_if = "is_default")]
    pub onboarding_status: OnboardingStatus,
    /// Backwards compatible project directory setting.
    #[serde(default, alias = "projectDirectory", skip_serializing_if = "Option::is_none")]
    pub project_directory: Option<std::path::PathBuf>,
    /// Backwards compatible theme setting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub theme: Option<AppTheme>,
    /// The hue of the primary theme color for the app.
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "themeColor")]
    pub theme_color: Option<FloatOrInt>,
    /// Whether or not Screen Space Ambient Occlusion (SSAO) is enabled.
    #[serde(default, alias = "enableSSAO", skip_serializing_if = "Option::is_none")]
    pub enable_ssao: Option<bool>,
    /// Permanently dismiss the banner warning to download the desktop app.
    /// This setting only applies to the web app. And is temporary until we have Linux support.
    #[serde(default, alias = "dismissWebBanner", skip_serializing_if = "is_default")]
    pub dismiss_web_banner: bool,
    /// When the user is idle, and this is true, the stream will be torn down.
    #[serde(default, alias = "streamIdleMode", skip_serializing_if = "is_default")]
    stream_idle_mode: bool,
}

// TODO: When we remove backwards compatibility with the old settings file, we can remove this.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq)]
#[ts(export)]
#[serde(untagged)]
pub enum FloatOrInt {
    String(String),
    Float(f64),
    Int(i64),
}

impl From<FloatOrInt> for f64 {
    fn from(float_or_int: FloatOrInt) -> Self {
        match float_or_int {
            FloatOrInt::String(s) => s.parse().unwrap(),
            FloatOrInt::Float(f) => f,
            FloatOrInt::Int(i) => i as f64,
        }
    }
}

impl From<FloatOrInt> for AppColor {
    fn from(float_or_int: FloatOrInt) -> Self {
        match float_or_int {
            FloatOrInt::String(s) => s.parse::<f64>().unwrap().into(),
            FloatOrInt::Float(f) => f.into(),
            FloatOrInt::Int(i) => (i as f64).into(),
        }
    }
}

/// The settings for the theme of the app.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct AppearanceSettings {
    /// The overall theme of the app.
    #[serde(default, skip_serializing_if = "is_default")]
    pub theme: AppTheme,
    /// The hue of the primary theme color for the app.
    #[serde(default, skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub color: AppColor,
}

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq)]
#[ts(export)]
#[serde(transparent)]
pub struct AppColor(pub f64);

impl Default for AppColor {
    fn default() -> Self {
        Self(DEFAULT_THEME_COLOR)
    }
}

impl From<AppColor> for f64 {
    fn from(color: AppColor) -> Self {
        color.0
    }
}

impl From<f64> for AppColor {
    fn from(color: f64) -> Self {
        Self(color)
    }
}

impl Validate for AppColor {
    fn validate(&self) -> Result<(), validator::ValidationErrors> {
        if !self.0.validate_range(Some(0.0), None, None, Some(360.0)) {
            let mut errors = validator::ValidationErrors::new();
            let mut err = validator::ValidationError::new("color");
            err.add_param(std::borrow::Cow::from("min"), &0.0);
            err.add_param(std::borrow::Cow::from("exclusive_max"), &360.0);
            errors.add("color", err);
            return Err(errors);
        }
        Ok(())
    }
}

/// The overall appearance of the app.
#[derive(
    Debug, Default, Copy, Clone, Deserialize, Serialize, JsonSchema, Display, FromStr, ts_rs::TS, PartialEq, Eq,
)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
#[display(style = "snake_case")]
pub enum AppTheme {
    /// A light theme.
    Light,
    /// A dark theme.
    Dark,
    /// Use the system theme.
    /// This will use dark theme if the system theme is dark, and light theme if the system theme is light.
    #[default]
    System,
}

impl From<AppTheme> for kittycad::types::Color {
    fn from(theme: AppTheme) -> Self {
        match theme {
            AppTheme::Light => kittycad::types::Color {
                r: 249.0 / 255.0,
                g: 249.0 / 255.0,
                b: 249.0 / 255.0,
                a: 1.0,
            },
            AppTheme::Dark => kittycad::types::Color {
                r: 28.0 / 255.0,
                g: 28.0 / 255.0,
                b: 28.0 / 255.0,
                a: 1.0,
            },
            AppTheme::System => {
                // TODO: Check the system setting for the user.
                todo!()
            }
        }
    }
}

/// Settings that affect the behavior while modeling.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Eq, Validate)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub struct ModelingSettings {
    /// The default unit to use in modeling dimensions.
    #[serde(default, alias = "defaultUnit", skip_serializing_if = "is_default")]
    pub base_unit: UnitLength,
    /// The controls for how to navigate the 3D view.
    #[serde(default, alias = "mouseControls", skip_serializing_if = "is_default")]
    pub mouse_controls: MouseControlType,
    /// Highlight edges of 3D objects?
    #[serde(default, alias = "highlightEdges", skip_serializing_if = "is_default")]
    pub highlight_edges: DefaultTrue,
    /// Whether to show the debug panel, which lets you see various states
    /// of the app to aid in development.
    #[serde(default, alias = "showDebugPanel", skip_serializing_if = "is_default")]
    pub show_debug_panel: bool,
    /// Whether or not Screen Space Ambient Occlusion (SSAO) is enabled.
    #[serde(default, skip_serializing_if = "is_default")]
    pub enable_ssao: DefaultTrue,
    /// Whether or not to show a scale grid in the 3D modeling view
    #[serde(default, alias = "showScaleGrid", skip_serializing_if = "is_default")]
    pub show_scale_grid: bool,
}

#[derive(Debug, Copy, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Eq)]
#[ts(export)]
#[serde(transparent)]
pub struct DefaultTrue(pub bool);

impl Default for DefaultTrue {
    fn default() -> Self {
        Self(true)
    }
}

impl From<DefaultTrue> for bool {
    fn from(default_true: DefaultTrue) -> Self {
        default_true.0
    }
}

impl From<bool> for DefaultTrue {
    fn from(b: bool) -> Self {
        Self(b)
    }
}

/// The valid types of length units.
#[derive(
    Debug, Default, Eq, PartialEq, Copy, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, Display, FromStr,
)]
#[cfg_attr(feature = "pyo3", pyo3::pyclass(eq, eq_int))]
#[ts(export)]
#[serde(rename_all = "lowercase")]
#[display(style = "lowercase")]
pub enum UnitLength {
    /// Centimeters <https://en.wikipedia.org/wiki/Centimeter>
    Cm,
    /// Feet <https://en.wikipedia.org/wiki/Foot_(unit)>
    Ft,
    /// Inches <https://en.wikipedia.org/wiki/Inch>
    In,
    /// Meters <https://en.wikipedia.org/wiki/Meter>
    M,
    /// Millimeters <https://en.wikipedia.org/wiki/Millimeter>
    #[default]
    Mm,
    /// Yards <https://en.wikipedia.org/wiki/Yard>
    Yd,
}

impl From<kittycad::types::UnitLength> for UnitLength {
    fn from(unit: kittycad::types::UnitLength) -> Self {
        match unit {
            kittycad::types::UnitLength::Cm => UnitLength::Cm,
            kittycad::types::UnitLength::Ft => UnitLength::Ft,
            kittycad::types::UnitLength::In => UnitLength::In,
            kittycad::types::UnitLength::M => UnitLength::M,
            kittycad::types::UnitLength::Mm => UnitLength::Mm,
            kittycad::types::UnitLength::Yd => UnitLength::Yd,
        }
    }
}

impl From<UnitLength> for kittycad::types::UnitLength {
    fn from(unit: UnitLength) -> Self {
        match unit {
            UnitLength::Cm => kittycad::types::UnitLength::Cm,
            UnitLength::Ft => kittycad::types::UnitLength::Ft,
            UnitLength::In => kittycad::types::UnitLength::In,
            UnitLength::M => kittycad::types::UnitLength::M,
            UnitLength::Mm => kittycad::types::UnitLength::Mm,
            UnitLength::Yd => kittycad::types::UnitLength::Yd,
        }
    }
}

/// The types of controls for how to navigate the 3D view.
#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, Display, FromStr)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
#[display(style = "snake_case")]
pub enum MouseControlType {
    #[default]
    #[display("kittycad")]
    #[serde(rename = "kittycad", alias = "KittyCAD")]
    KittyCad,
    #[display("onshape")]
    #[serde(rename = "onshape", alias = "OnShape")]
    OnShape,
    #[serde(alias = "Trackpad Friendly")]
    TrackpadFriendly,
    #[serde(alias = "Solidworks")]
    Solidworks,
    #[serde(alias = "NX")]
    Nx,
    #[serde(alias = "Creo")]
    Creo,
    #[display("autocad")]
    #[serde(rename = "autocad", alias = "AutoCAD")]
    AutoCad,
}

/// Settings that affect the behavior of the KCL text editor.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Eq, Validate)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub struct TextEditorSettings {
    /// Whether to wrap text in the editor or overflow with scroll.
    #[serde(default, alias = "textWrapping", skip_serializing_if = "is_default")]
    pub text_wrapping: DefaultTrue,
    /// Whether to make the cursor blink in the editor.
    #[serde(default, alias = "blinkingCursor", skip_serializing_if = "is_default")]
    pub blinking_cursor: DefaultTrue,
}

/// Settings that affect the behavior of project management.
#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Eq, Validate)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub struct ProjectSettings {
    /// The directory to save and load projects from.
    #[serde(default, skip_serializing_if = "is_default")]
    pub directory: std::path::PathBuf,
    /// The default project name to use when creating a new project.
    #[serde(default, alias = "defaultProjectName", skip_serializing_if = "is_default")]
    pub default_project_name: ProjectNameTemplate,
}

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Eq)]
#[ts(export)]
#[serde(transparent)]
pub struct ProjectNameTemplate(pub String);

impl Default for ProjectNameTemplate {
    fn default() -> Self {
        Self(DEFAULT_PROJECT_NAME_TEMPLATE.to_string())
    }
}

impl From<ProjectNameTemplate> for String {
    fn from(project_name: ProjectNameTemplate) -> Self {
        project_name.0
    }
}

impl From<String> for ProjectNameTemplate {
    fn from(s: String) -> Self {
        Self(s)
    }
}

/// Settings that affect the behavior of the command bar.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Eq, Validate)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub struct CommandBarSettings {
    /// Whether to include settings in the command bar.
    #[serde(default, alias = "includeSettings", skip_serializing_if = "is_default")]
    pub include_settings: DefaultTrue,
}

/// The types of onboarding status.
#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, Display, FromStr)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
#[display(style = "snake_case")]
pub enum OnboardingStatus {
    /// The user has completed onboarding.
    Completed,
    /// The user has not completed onboarding.
    #[default]
    Incomplete,
    /// The user has dismissed onboarding.
    Dismissed,

    // Routes
    #[serde(rename = "/")]
    #[display("/")]
    Index,
    #[serde(rename = "/camera")]
    #[display("/camera")]
    Camera,
    #[serde(rename = "/streaming")]
    #[display("/streaming")]
    Streaming,
    #[serde(rename = "/editor")]
    #[display("/editor")]
    Editor,
    #[serde(rename = "/parametric-modeling")]
    #[display("/parametric-modeling")]
    ParametricModeling,
    #[serde(rename = "/interactive-numbers")]
    #[display("/interactive-numbers")]
    InteractiveNumbers,
    #[serde(rename = "/command-k")]
    #[display("/command-k")]
    CommandK,
    #[serde(rename = "/user-menu")]
    #[display("/user-menu")]
    UserMenu,
    #[serde(rename = "/project-menu")]
    #[display("/project-menu")]
    ProjectMenu,
    #[serde(rename = "/export")]
    #[display("/export")]
    Export,
    #[serde(rename = "/move")]
    #[display("/move")]
    Move,
    #[serde(rename = "/sketching")]
    #[display("/sketching")]
    Sketching,
    #[serde(rename = "/future-work")]
    #[display("/future-work")]
    FutureWork,
}

fn is_default<T: Default + PartialEq>(t: &T) -> bool {
    t == &T::default()
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;
    use validator::Validate;

    use super::{
        AppColor, AppSettings, AppTheme, AppearanceSettings, CommandBarSettings, Configuration, ModelingSettings,
        OnboardingStatus, ProjectSettings, Settings, TextEditorSettings, UnitLength,
    };

    #[test]
    // Test that we can deserialize a project file from the old format.
    // TODO: We can remove this functionality after a few versions.
    fn test_backwards_compatible_project_settings_file_pw() {
        let old_project_file = r#"[settings.app]
theme = "dark"
onboardingStatus = "dismissed"
projectDirectory = ""
enableSSAO = false

[settings.modeling]
defaultUnit = "in"
mouseControls = "KittyCAD"
showDebugPanel = true

[settings.projects]
defaultProjectName = "project-$nnn"

[settings.textEditor]
textWrapping = true
#"#;

        //let parsed = toml::from_str::<Configuration(old_project_file).unwrap();
        let parsed = Configuration::backwards_compatible_toml_parse(old_project_file).unwrap();
        assert_eq!(
            parsed,
            Configuration {
                settings: Settings {
                    app: AppSettings {
                        appearance: AppearanceSettings {
                            theme: AppTheme::Dark,
                            color: Default::default()
                        },
                        onboarding_status: OnboardingStatus::Dismissed,
                        project_directory: None,
                        theme: None,
                        theme_color: None,
                        dismiss_web_banner: false,
                        enable_ssao: None,
                        stream_idle_mode: false,
                    },
                    modeling: ModelingSettings {
                        base_unit: UnitLength::In,
                        mouse_controls: Default::default(),
                        highlight_edges: Default::default(),
                        show_debug_panel: true,
                        enable_ssao: false.into(),
                        show_scale_grid: false,
                    },
                    text_editor: TextEditorSettings {
                        text_wrapping: true.into(),
                        blinking_cursor: true.into()
                    },
                    project: Default::default(),
                    command_bar: CommandBarSettings {
                        include_settings: true.into()
                    },
                }
            }
        );
    }

    #[test]
    // Test that we can deserialize a project file from the old format.
    // TODO: We can remove this functionality after a few versions.
    fn test_backwards_compatible_project_settings_file() {
        let old_project_file = r#"[settings.app]
theme = "dark"
themeColor = "138"

[settings.modeling]
defaultUnit = "yd"
showDebugPanel = true

[settings.textEditor]
textWrapping = false
blinkingCursor = false

[settings.commandBar]
includeSettings = false
#"#;

        //let parsed = toml::from_str::<Configuration(old_project_file).unwrap();
        let parsed = Configuration::backwards_compatible_toml_parse(old_project_file).unwrap();
        assert_eq!(
            parsed,
            Configuration {
                settings: Settings {
                    app: AppSettings {
                        appearance: AppearanceSettings {
                            theme: AppTheme::Dark,
                            color: 138.0.into()
                        },
                        onboarding_status: Default::default(),
                        project_directory: None,
                        theme: None,
                        theme_color: None,
                        dismiss_web_banner: false,
                        enable_ssao: None,
                        stream_idle_mode: false,
                    },
                    modeling: ModelingSettings {
                        base_unit: UnitLength::Yd,
                        mouse_controls: Default::default(),
                        highlight_edges: Default::default(),
                        show_debug_panel: true,
                        enable_ssao: true.into(),
                        show_scale_grid: false,
                    },
                    text_editor: TextEditorSettings {
                        text_wrapping: false.into(),
                        blinking_cursor: false.into()
                    },
                    project: Default::default(),
                    command_bar: CommandBarSettings {
                        include_settings: false.into()
                    },
                }
            }
        );
    }

    #[test]
    // Test that we can deserialize a app settings file from the old format.
    // TODO: We can remove this functionality after a few versions.
    fn test_backwards_compatible_app_settings_file() {
        let old_app_settings_file = r#"[settings.app]
onboardingStatus = "dismissed"
projectDirectory = "/Users/macinatormax/Documents/kittycad-modeling-projects"
theme = "dark"
themeColor = "138"

[settings.modeling]
defaultUnit = "yd"
showDebugPanel = true

[settings.textEditor]
textWrapping = false
blinkingCursor = false

[settings.commandBar]
includeSettings = false

[settings.projects]
defaultProjectName = "projects-$nnn"
#"#;

        //let parsed = toml::from_str::<Configuration>(old_app_settings_file).unwrap();
        let parsed = Configuration::backwards_compatible_toml_parse(old_app_settings_file).unwrap();
        assert_eq!(
            parsed,
            Configuration {
                settings: Settings {
                    app: AppSettings {
                        appearance: AppearanceSettings {
                            theme: AppTheme::Dark,
                            color: 138.0.into()
                        },
                        onboarding_status: OnboardingStatus::Dismissed,
                        project_directory: None,
                        theme: None,
                        theme_color: None,
                        dismiss_web_banner: false,
                        enable_ssao: None,
                        stream_idle_mode: false,
                    },
                    modeling: ModelingSettings {
                        base_unit: UnitLength::Yd,
                        mouse_controls: Default::default(),
                        highlight_edges: Default::default(),
                        show_debug_panel: true,
                        enable_ssao: true.into(),
                        show_scale_grid: false,
                    },
                    text_editor: TextEditorSettings {
                        text_wrapping: false.into(),
                        blinking_cursor: false.into()
                    },
                    project: ProjectSettings {
                        directory: "/Users/macinatormax/Documents/kittycad-modeling-projects".into(),
                        default_project_name: "projects-$nnn".to_string().into()
                    },
                    command_bar: CommandBarSettings {
                        include_settings: false.into()
                    },
                }
            }
        );

        // Write the file back out.
        let serialized = toml::to_string(&parsed).unwrap();
        assert_eq!(
            serialized,
            r#"[settings.app]
onboarding_status = "dismissed"

[settings.app.appearance]
theme = "dark"
color = 138.0

[settings.modeling]
base_unit = "yd"
show_debug_panel = true

[settings.text_editor]
text_wrapping = false
blinking_cursor = false

[settings.project]
directory = "/Users/macinatormax/Documents/kittycad-modeling-projects"
default_project_name = "projects-$nnn"

[settings.command_bar]
include_settings = false
"#
        );
    }

    #[test]
    fn test_settings_backwards_compat_partial() {
        let partial_settings_file = r#"[settings.app]
onboardingStatus = "dismissed"
projectDirectory = "/Users/macinatormax/Documents/kittycad-modeling-projects""#;

        //let parsed = toml::from_str::<Configuration>(partial_settings_file).unwrap();
        let parsed = Configuration::backwards_compatible_toml_parse(partial_settings_file).unwrap();
        assert_eq!(
            parsed,
            Configuration {
                settings: Settings {
                    app: AppSettings {
                        appearance: AppearanceSettings {
                            theme: AppTheme::System,
                            color: Default::default()
                        },
                        onboarding_status: OnboardingStatus::Dismissed,
                        project_directory: None,
                        theme: None,
                        theme_color: None,
                        dismiss_web_banner: false,
                        enable_ssao: None,
                        stream_idle_mode: false,
                    },
                    modeling: ModelingSettings {
                        base_unit: UnitLength::Mm,
                        mouse_controls: Default::default(),
                        highlight_edges: true.into(),
                        show_debug_panel: false,
                        enable_ssao: true.into(),
                        show_scale_grid: false,
                    },
                    text_editor: TextEditorSettings {
                        text_wrapping: true.into(),
                        blinking_cursor: true.into()
                    },
                    project: ProjectSettings {
                        directory: "/Users/macinatormax/Documents/kittycad-modeling-projects".into(),
                        default_project_name: "project-$nnn".to_string().into()
                    },
                    command_bar: CommandBarSettings {
                        include_settings: true.into()
                    },
                }
            }
        );

        // Write the file back out.
        let serialized = toml::to_string(&parsed).unwrap();
        assert_eq!(
            serialized,
            r#"[settings.app]
onboarding_status = "dismissed"

[settings.project]
directory = "/Users/macinatormax/Documents/kittycad-modeling-projects"
"#
        );
    }

    #[test]
    fn test_settings_empty_file_parses() {
        let empty_settings_file = r#""#;

        let parsed = toml::from_str::<Configuration>(empty_settings_file).unwrap();
        assert_eq!(parsed, Configuration::default());

        // Write the file back out.
        let serialized = toml::to_string(&parsed).unwrap();
        assert_eq!(serialized, r#""#);

        let parsed = Configuration::backwards_compatible_toml_parse(empty_settings_file).unwrap();
        assert_eq!(parsed, Configuration::default());
    }

    #[test]
    fn test_color_validation() {
        let color = AppColor(360.0);

        let result = color.validate();
        if let Ok(r) = result {
            panic!("Expected an error, but got success: {:?}", r);
        }
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("color: Validation error: color"));

        let appearance = AppearanceSettings {
            theme: AppTheme::System,
            color: AppColor(361.5),
        };
        let result = appearance.validate();
        if let Ok(r) = result {
            panic!("Expected an error, but got success: {:?}", r);
        }
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("color: Validation error: color"));
    }

    #[test]
    fn test_settings_color_validation_error() {
        let settings_file = r#"[settings.app.appearance]
color = 1567.4"#;

        let result = Configuration::backwards_compatible_toml_parse(settings_file);
        if let Ok(r) = result {
            panic!("Expected an error, but got success: {:?}", r);
        }
        assert!(result.is_err());

        assert!(result
            .unwrap_err()
            .to_string()
            .contains("color: Validation error: color"));
    }

    #[tokio::test]
    async fn test_create_new_project_directory_no_initial_code() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = format!("test_project_{}", uuid::Uuid::new_v4());
        let project = settings
            .create_new_project_directory(&project_name, None)
            .await
            .unwrap();

        assert_eq!(project.file.name, project_name);
        assert_eq!(
            project.file.path,
            settings
                .settings
                .project
                .directory
                .join(&project_name)
                .to_string_lossy()
        );
        assert_eq!(project.kcl_file_count, 1);
        assert_eq!(project.directory_count, 0);
        assert_eq!(
            project.default_file,
            std::path::Path::new(&project.file.path)
                .join(super::DEFAULT_PROJECT_KCL_FILE)
                .to_string_lossy()
        );

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }

    #[tokio::test]
    async fn test_create_new_project_directory_empty_name() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = "";
        let project = settings.create_new_project_directory(project_name, None).await;

        assert!(project.is_err());
        assert_eq!(project.unwrap_err().to_string(), "Project name cannot be empty.");

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }

    #[tokio::test]
    async fn test_create_new_project_directory_with_initial_code() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = format!("test_project_{}", uuid::Uuid::new_v4());
        let initial_code = "initial code";
        let project = settings
            .create_new_project_directory(&project_name, Some(initial_code))
            .await
            .unwrap();

        assert_eq!(project.file.name, project_name);
        assert_eq!(
            project.file.path,
            settings
                .settings
                .project
                .directory
                .join(&project_name)
                .to_string_lossy()
        );
        assert_eq!(project.kcl_file_count, 1);
        assert_eq!(project.directory_count, 0);
        assert_eq!(
            project.default_file,
            std::path::Path::new(&project.file.path)
                .join(super::DEFAULT_PROJECT_KCL_FILE)
                .to_string_lossy()
        );
        assert_eq!(
            tokio::fs::read_to_string(&project.default_file).await.unwrap(),
            initial_code
        );

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }

    #[tokio::test]
    async fn test_list_projects() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = format!("test_project_{}", uuid::Uuid::new_v4());
        let project = settings
            .create_new_project_directory(&project_name, None)
            .await
            .unwrap();

        let projects = settings.list_projects().await.unwrap();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].file.name, project_name);
        assert_eq!(projects[0].file.path, project.file.path);
        assert_eq!(projects[0].kcl_file_count, 1);
        assert_eq!(projects[0].directory_count, 0);
        assert_eq!(projects[0].default_file, project.default_file);

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }

    #[tokio::test]
    async fn test_list_projects_with_rando_files() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = format!("test_project_{}", uuid::Uuid::new_v4());
        let project = settings
            .create_new_project_directory(&project_name, None)
            .await
            .unwrap();

        // Create a random file in the root project directory.
        let random_file = std::path::Path::new(&settings.settings.project.directory).join("random_file.txt");
        tokio::fs::write(&random_file, "random file").await.unwrap();

        let projects = settings.list_projects().await.unwrap();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].file.name, project_name);
        assert_eq!(projects[0].file.path, project.file.path);
        assert_eq!(projects[0].kcl_file_count, 1);
        assert_eq!(projects[0].directory_count, 0);
        assert_eq!(projects[0].default_file, project.default_file);

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }

    #[tokio::test]
    async fn test_list_projects_with_hidden_dir() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = format!("test_project_{}", uuid::Uuid::new_v4());
        let project = settings
            .create_new_project_directory(&project_name, None)
            .await
            .unwrap();

        // Create a hidden directory in the project directory.
        let hidden_dir = std::path::Path::new(&settings.settings.project.directory).join(".git");
        tokio::fs::create_dir_all(&hidden_dir).await.unwrap();

        let projects = settings.list_projects().await.unwrap();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].file.name, project_name);
        assert_eq!(projects[0].file.path, project.file.path);
        assert_eq!(projects[0].kcl_file_count, 1);
        assert_eq!(projects[0].directory_count, 0);
        assert_eq!(projects[0].default_file, project.default_file);

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }

    #[tokio::test]
    async fn test_list_projects_with_dir_not_containing_kcl_file() {
        let mut settings = Configuration::default();
        settings.settings.project.directory =
            std::env::temp_dir().join(format!("test_project_{}", uuid::Uuid::new_v4()));

        let project_name = format!("test_project_{}", uuid::Uuid::new_v4());
        let project = settings
            .create_new_project_directory(&project_name, None)
            .await
            .unwrap();

        // Create a directory in the project directory that doesn't contain a KCL file.
        let random_dir = std::path::Path::new(&settings.settings.project.directory).join("random_dir");
        tokio::fs::create_dir_all(&random_dir).await.unwrap();

        let projects = settings.list_projects().await.unwrap();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].file.name, project_name);
        assert_eq!(projects[0].file.path, project.file.path);
        assert_eq!(projects[0].kcl_file_count, 1);
        assert_eq!(projects[0].directory_count, 0);
        assert_eq!(projects[0].default_file, project.default_file);

        std::fs::remove_dir_all(&settings.settings.project.directory).unwrap();
    }
}