spacetimedb-cli 0.3.3

A command line interface for SpacetimeDB
Documentation
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
use std::fmt::{self, Write};

use convert_case::{Case, Casing};
use spacetimedb_lib::sats::{AlgebraicType, AlgebraicTypeRef, BuiltinType, MapType, ProductType};
use spacetimedb_lib::{ReducerDef, TableDef, TupleDef, TypeDef};

use super::code_indenter::CodeIndenter;
use super::{GenCtx, INDENT};

const NAMESPACE: &str = "SpacetimeDB";

enum MaybePrimitive<'a> {
    Primitive(&'static str),
    Array { ty: &'a AlgebraicType },
    Map(&'a MapType),
}

fn maybe_primitive(b: &BuiltinType) -> MaybePrimitive {
    MaybePrimitive::Primitive(match b {
        BuiltinType::Bool => "bool",
        BuiltinType::I8 => "sbyte",
        BuiltinType::U8 => "byte",
        BuiltinType::I16 => "short",
        BuiltinType::U16 => "ushort",
        BuiltinType::I32 => "int",
        BuiltinType::U32 => "uint",
        BuiltinType::I64 => "long",
        BuiltinType::U64 => "ulong",
        // BuiltinType::I128 => "int128", Not a supported type in csharp
        // BuiltinType::U128 => "uint128", Not a supported type in csharp
        BuiltinType::I128 => panic!("i128 not supported for csharp"),
        BuiltinType::U128 => panic!("i128 not supported for csharp"),
        BuiltinType::String => "string",
        BuiltinType::F32 => "float",
        BuiltinType::F64 => "double",
        BuiltinType::Array { ty } => return MaybePrimitive::Array { ty },
        BuiltinType::Map(m) => return MaybePrimitive::Map(m),
    })
}

fn ty_fmt<'a>(ctx: &'a GenCtx, ty: &'a AlgebraicType) -> impl fmt::Display + 'a {
    fmt_fn(move |f| match ty {
        TypeDef::Sum(_) => unimplemented!(),
        TypeDef::Product(_) => unimplemented!(),
        TypeDef::Builtin(b) => match maybe_primitive(b) {
            MaybePrimitive::Primitive(p) => f.write_str(p),
            MaybePrimitive::Array { ty } if *ty == AlgebraicType::U8 => f.write_str("byte[]"),
            MaybePrimitive::Array { ty } => {
                write!(f, "System.Collections.Generic.List<{}>", ty_fmt(ctx, ty))
            }
            MaybePrimitive::Map(ty) => {
                write!(
                    f,
                    "System.Collections.Generic.Dictionary<{}, {}>",
                    ty_fmt(ctx, &ty.ty),
                    ty_fmt(ctx, &ty.key_ty)
                )
            }
        },
        TypeDef::Ref(r) => f.write_str(csharp_typename(ctx, *r)),
    })
}
fn convert_builtintype<'a>(
    ctx: &'a GenCtx,
    vecnest: usize,
    b: &'a BuiltinType,
    value: impl fmt::Display + 'a,
) -> impl fmt::Display + 'a {
    fmt_fn(move |f| match maybe_primitive(b) {
        MaybePrimitive::Primitive(_) => {
            write!(f, "{value}.As{b:?}()")
        }
        MaybePrimitive::Array { ty } if *ty == AlgebraicType::U8 => {
            write!(f, "{value}.AsBytes()")
        }
        MaybePrimitive::Array { ty } => {
            let csharp_type = ty_fmt(ctx, ty);
            writeln!(
                f,
                "((System.Func<System.Collections.Generic.List<{csharp_type}>>)(() => {{"
            )?;
            writeln!(
                f,
                "\tvar vec{vecnest} = new System.Collections.Generic.List<{}>();",
                csharp_type
            )?;
            writeln!(f, "\tvar vec{vecnest}_source = {value}.AsArray();",)?;
            writeln!(f, "\tforeach(var entry in vec{vecnest}_source!)")?;
            writeln!(f, "\t{{")?;
            writeln!(
                f,
                "\t\tvec{vecnest}.Add({});",
                convert_type(ctx, vecnest + 1, ty, "entry")
            )?;
            writeln!(f, "\t}}")?;
            writeln!(f, "\treturn vec{vecnest};")?;
            write!(f, "}}))()")
        }
        MaybePrimitive::Map(_) => todo!(),
    })
}

fn convert_type<'a>(
    ctx: &'a GenCtx,
    vecnest: usize,
    ty: &'a AlgebraicType,
    value: impl fmt::Display + 'a,
) -> impl fmt::Display + 'a {
    fmt_fn(move |f| match ty {
        TypeDef::Product(_) => unimplemented!(),
        TypeDef::Sum(_) => unimplemented!(),
        TypeDef::Builtin(b) => fmt::Display::fmt(&convert_builtintype(ctx, vecnest, b, &value), f),
        TypeDef::Ref(r) => {
            let name = csharp_typename(ctx, *r);
            write!(f, "({name}){value}",)
        }
    })
}

// can maybe do something fancy with this in the future
fn csharp_typename(ctx: &GenCtx, typeref: AlgebraicTypeRef) -> &str {
    ctx.names[typeref.idx()].as_deref().expect("tuples should have names")
}

fn fmt_fn(f: impl Fn(&mut fmt::Formatter) -> fmt::Result) -> impl fmt::Display {
    struct FDisplay<F>(F);
    impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for FDisplay<F> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            (self.0)(f)
        }
    }
    FDisplay(f)
}

macro_rules! indent_scope {
    ($x:ident) => {
        let mut $x = $x.indented(1);
    };
}

fn convert_algebraic_type<'a>(ctx: &'a GenCtx, ty: &'a TypeDef) -> impl fmt::Display + 'a {
    fmt_fn(move |f| match ty {
        AlgebraicType::Product(product_type) => write!(f, "{}", convert_product_type(ctx, product_type)),
        AlgebraicType::Sum(_) => unimplemented!(),
        AlgebraicType::Builtin(b) => match maybe_primitive(b) {
            MaybePrimitive::Primitive(_) => {
                write!(
                    f,
                    "SpacetimeDB.SATS.AlgebraicType.CreatePrimitiveType(SpacetimeDB.SATS.BuiltinType.Type.{:?})",
                    b
                )
            }
            MaybePrimitive::Array { ty } => write!(
                f,
                "SpacetimeDB.SATS.AlgebraicType.CreateArrayType({})",
                convert_algebraic_type(ctx, ty)
            ),
            MaybePrimitive::Map(_) => todo!(),
        },
        AlgebraicType::Ref(r) => write!(f, "SpacetimeDB.{}.GetAlgebraicType()", csharp_typename(ctx, *r)),
    })
}

fn convert_product_type<'a>(ctx: &'a GenCtx, product_type: &'a ProductType) -> impl fmt::Display + 'a {
    fmt_fn(move |f| {
        writeln!(
            f,
            "SpacetimeDB.SATS.AlgebraicType.CreateProductType(new SpacetimeDB.SATS.ProductTypeElement[]"
        )?;
        writeln!(f, "{{")?;
        for (_, elem) in product_type.elements.iter().enumerate() {
            writeln!(
                f,
                "{INDENT}new SpacetimeDB.SATS.ProductTypeElement({}, {}),",
                elem.name
                    .to_owned()
                    .map(|s| format!("\"{}\"", s))
                    .unwrap_or("null".into()),
                convert_algebraic_type(ctx, &elem.algebraic_type)
            )?;
        }
        write!(f, "}})")
    })
}

pub fn autogen_csharp_tuple(ctx: &GenCtx, name: &str, tuple: &TupleDef) -> String {
    autogen_csharp_product_table_common(ctx, name, tuple, None)
}
pub fn autogen_csharp_table(ctx: &GenCtx, name: &str, table: &TableDef) -> String {
    let tuple = ctx.typespace[table.data].as_product().unwrap();
    autogen_csharp_product_table_common(ctx, name, tuple, Some(&table.unique_columns))
}
fn autogen_csharp_product_table_common(
    ctx: &GenCtx,
    name: &str,
    product_type: &ProductType,
    unique_columns: Option<&[u8]>,
) -> String {
    let mut output = CodeIndenter::new(String::new());

    let struct_name_pascal_case = name.replace("r#", "").to_case(Case::Pascal);

    writeln!(
        output,
        "// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE",
    )
    .unwrap();
    writeln!(output, "// WILL NOT BE SAVED. MODIFY TABLES IN RUST INSTEAD.").unwrap();
    writeln!(output).unwrap();

    writeln!(output, "using System;").unwrap();
    writeln!(output).unwrap();

    writeln!(output, "namespace {NAMESPACE}").unwrap();
    writeln!(output, "{{").unwrap();
    {
        indent_scope!(output);
        writeln!(
            output,
            "public partial class {struct_name_pascal_case} : IDatabaseTable"
        )
        .unwrap();
        writeln!(output, "{{").unwrap();
        {
            indent_scope!(output);

            for field in &product_type.elements {
                let field_name = field
                    .name
                    .as_ref()
                    .expect("autogen'd tuples should have field names")
                    .replace("r#", "");
                writeln!(output, "[Newtonsoft.Json.JsonProperty(\"{field_name}\")]").unwrap();
                writeln!(
                    output,
                    "public {} {};",
                    ty_fmt(ctx, &field.algebraic_type),
                    field_name.to_case(Case::Pascal)
                )
                .unwrap();
            }

            writeln!(output).unwrap();

            writeln!(
                output,
                "public static SpacetimeDB.SATS.AlgebraicType GetAlgebraicType()"
            )
            .unwrap();
            writeln!(output, "{{").unwrap();
            {
                indent_scope!(output);
                writeln!(output, "return {};", convert_product_type(ctx, product_type)).unwrap();
            }
            writeln!(output, "}}").unwrap();
            writeln!(output).unwrap();

            write!(
                output,
                "{}",
                autogen_csharp_product_value_to_struct(ctx, &struct_name_pascal_case, product_type)
            )
            .unwrap();

            writeln!(output).unwrap();

            // If this is a table, we want to include functions for accessing the table data
            if let Some(unique_columns) = unique_columns {
                // Insert the funcs for accessing this struct
                autogen_csharp_access_funcs_for_struct(
                    &mut output,
                    &struct_name_pascal_case,
                    product_type,
                    name,
                    unique_columns,
                );

                writeln!(
                    output,
                    "public static event Action<{struct_name_pascal_case}> OnInsert;"
                )
                .unwrap();
                writeln!(
                    output,
                    "public static event Action<{struct_name_pascal_case}, {struct_name_pascal_case}> OnUpdate;"
                )
                .unwrap();
                writeln!(
                    output,
                    "public static event Action<{struct_name_pascal_case}> OnDelete;"
                )
                .unwrap();

                writeln!(
                    output,
                    "public static event Action<NetworkManager.TableOp, {struct_name_pascal_case}, {struct_name_pascal_case}> OnRowUpdate;"
                )
                .unwrap();

                writeln!(output).unwrap();

                writeln!(output, "public static void OnInsertEvent(object newValue)").unwrap();
                writeln!(output, "{{").unwrap();
                {
                    indent_scope!(output);
                    writeln!(output, "OnInsert?.Invoke(({struct_name_pascal_case})newValue);").unwrap();
                }
                writeln!(output, "}}").unwrap();
                writeln!(output).unwrap();

                writeln!(
                    output,
                    "public static void OnUpdateEvent(object oldValue, object newValue)"
                )
                .unwrap();
                writeln!(output, "{{").unwrap();
                {
                    indent_scope!(output);
                    writeln!(
                        output,
                        "OnUpdate?.Invoke(({struct_name_pascal_case})oldValue,({struct_name_pascal_case})newValue);"
                    )
                    .unwrap();
                }
                writeln!(output, "}}").unwrap();
                writeln!(output).unwrap();

                writeln!(output, "public static void OnDeleteEvent(object oldValue)").unwrap();
                writeln!(output, "{{").unwrap();
                {
                    indent_scope!(output);
                    writeln!(output, "OnDelete?.Invoke(({struct_name_pascal_case})oldValue);").unwrap();
                }
                writeln!(output, "}}").unwrap();
                writeln!(output).unwrap();

                writeln!(
                    output,
                    "public static void OnRowUpdateEvent(NetworkManager.TableOp op, object oldValue, object newValue)"
                )
                .unwrap();
                writeln!(output, "{{").unwrap();
                {
                    indent_scope!(output);
                    writeln!(
                        output,
                        "OnRowUpdate?.Invoke(op, ({struct_name_pascal_case})oldValue,({struct_name_pascal_case})newValue);"
                    )
                    .unwrap();
                }
                writeln!(output, "}}").unwrap();
            }
        }
        writeln!(output, "}}").unwrap();
    }
    writeln!(output, "}}").unwrap();

    output.into_inner()
}

fn autogen_csharp_product_value_to_struct(
    ctx: &GenCtx,
    struct_name_pascal_case: &str,
    product_type: &ProductType,
) -> String {
    let mut output_contents_header: String = String::new();
    let mut output_contents_return: String = String::new();

    writeln!(
        output_contents_header,
        "public static explicit operator {struct_name_pascal_case}(SpacetimeDB.SATS.AlgebraicValue value)",
    )
    .unwrap();
    writeln!(output_contents_header, "{{").unwrap();
    writeln!(output_contents_header, "\tvar productValue = value.AsProductValue();").unwrap();

    // vec conversion go here
    writeln!(output_contents_return, "\treturn new {}", struct_name_pascal_case).unwrap();
    writeln!(output_contents_return, "\t{{").unwrap();

    for (idx, field) in product_type.elements.iter().enumerate() {
        let field_name = field
            .name
            .as_ref()
            .expect("autogen'd product types should have field names");
        let field_type = &field.algebraic_type;
        let csharp_field_name = field_name.to_string().replace("r#", "").to_case(Case::Pascal);

        writeln!(
            output_contents_return,
            "\t\t{csharp_field_name} = {},",
            convert_type(ctx, 0, field_type, format_args!("productValue.elements[{idx}]"))
        )
        .unwrap();
    }

    // End Struct
    writeln!(output_contents_return, "\t}};").unwrap();
    // End Func
    writeln!(output_contents_return, "}}").unwrap();

    output_contents_header + &output_contents_return
}

fn indented_block<R>(output: &mut CodeIndenter<String>, f: impl FnOnce(&mut CodeIndenter<String>) -> R) -> R {
    writeln!(output, "{{").unwrap();
    let res = f(&mut output.indented(1));
    writeln!(output, "}}").unwrap();
    res
}

fn autogen_csharp_access_funcs_for_struct(
    output: &mut CodeIndenter<String>,
    struct_name_pascal_case: &str,
    product_type: &ProductType,
    table_name: &str,
    unique_columns: &[u8],
) {
    let it = Iterator::chain(
        unique_columns.iter().copied().zip(std::iter::repeat(true)),
        (0..product_type.elements.len())
            .map(|i| i as u8)
            .filter(|i| unique_columns.binary_search(i).is_err())
            .zip(std::iter::repeat(false)),
    );
    writeln!(
        output,
        "public static System.Collections.Generic.IEnumerable<{struct_name_pascal_case}> Iter()"
    )
    .unwrap();
    indented_block(output, |output| {
        writeln!(
            output,
            "foreach(var entry in NetworkManager.clientDB.GetEntries(\"{table_name}\"))",
        )
        .unwrap();
        indented_block(output, |output| {
            // TODO: best way to handle this?
            writeln!(output, "yield return ({struct_name_pascal_case})entry;").unwrap();
        });
    });

    writeln!(output, "public static int Count()").unwrap();
    indented_block(output, |output| {
        writeln!(output, "return NetworkManager.clientDB.Count(\"{table_name}\");",).unwrap();
    });

    for (col_i, is_unique) in it {
        let field = &product_type.elements[col_i as usize];
        let field_name = field.name.as_ref().expect("autogen'd tuples should have field names");
        let field_type = &field.algebraic_type;
        let csharp_field_name_pascal = field_name.replace("r#", "").to_case(Case::Pascal);

        let (field_type, csharp_field_type) = match field_type {
            AlgebraicType::Product(_) | AlgebraicType::Ref(_) => {
                // TODO: We don't allow filtering on tuples right now, its possible we may consider it for the future.
                continue;
            }
            AlgebraicType::Sum(_) => {
                // TODO: We don't allow filtering on enums right now, its possible we may consider it for the future.
                continue;
            }
            AlgebraicType::Builtin(b) => match maybe_primitive(b) {
                MaybePrimitive::Primitive(ty) => (format!("{:?}", b), ty),
                MaybePrimitive::Array { ty } => {
                    if let Some(BuiltinType::U8) = ty.as_builtin() {
                        // Do allow filtering for byte arrays
                        ("Bytes".into(), "byte[]")
                    } else {
                        // TODO: We don't allow filtering based on an array type, but we might want other functionality here in the future.
                        continue;
                    }
                }
                MaybePrimitive::Map(_) => {
                    // TODO: It would be nice to be able to say, give me all entries where this vec contains this value, which we can do.
                    continue;
                }
            },
        };

        let filter_return_type = fmt_fn(|f| {
            if is_unique {
                f.write_str(struct_name_pascal_case)
            } else {
                write!(f, "System.Collections.Generic.IEnumerable<{}>", struct_name_pascal_case)
            }
        });

        writeln!(
            output,
            "public static {filter_return_type} FilterBy{}({} value)",
            csharp_field_name_pascal, csharp_field_type
        )
        .unwrap();

        writeln!(output, "{{").unwrap();
        {
            indent_scope!(output);
            writeln!(
                output,
                "foreach(var entry in NetworkManager.clientDB.GetEntries(\"{}\"))",
                table_name
            )
            .unwrap();
            writeln!(output, "{{").unwrap();
            {
                indent_scope!(output);
                writeln!(output, "var productValue = entry.AsProductValue();").unwrap();
                writeln!(
                    output,
                    "var compareValue = ({})productValue.elements[{}].As{}();",
                    csharp_field_type, col_i, field_type
                )
                .unwrap();
                if csharp_field_type == "byte[]" {
                    writeln!(
                        output,
                        "static bool ByteArrayCompare(byte[] a1, byte[] a2)
{{
    if (a1.Length != a2.Length)
        return false;

    for (int i=0; i<a1.Length; i++)
        if (a1[i]!=a2[i])
            return false;

    return true;
}}"
                    )
                    .unwrap();
                    writeln!(output).unwrap();
                    writeln!(output, "if (ByteArrayCompare(compareValue, value)) {{").unwrap();
                    {
                        indent_scope!(output);
                        if is_unique {
                            writeln!(output, "return ({struct_name_pascal_case})entry;").unwrap();
                        } else {
                            writeln!(output, "yield return ({struct_name_pascal_case})entry;").unwrap();
                        }
                    }
                    writeln!(output, "}}").unwrap();
                } else {
                    writeln!(output, "if (compareValue == value) {{").unwrap();
                    {
                        indent_scope!(output);
                        if is_unique {
                            writeln!(output, "return ({struct_name_pascal_case})entry;").unwrap();
                        } else {
                            writeln!(output, "yield return ({struct_name_pascal_case})entry;").unwrap();
                        }
                    }
                    writeln!(output, "}}").unwrap();
                }
            }
            // End foreach
            writeln!(output, "}}").unwrap();

            if is_unique {
                writeln!(output, "return null;").unwrap();
            }
        }
        // End Func
        writeln!(output, "}}").unwrap();
        writeln!(output).unwrap();
    }
}

// fn convert_enumdef(tuple: &EnumDef) -> impl fmt::Display + '_ {
//     fmt_fn(move |f| {
//         writeln!(f, "TypeDef.Tuple(new ElementDef[]")?;
//         writeln!(f, "{{")?;
//         for (i, elem) in tuple.elements.iter().enumerate() {
//             let comma = if i == tuple.elements.len() - 1 { "" } else { "," };
//             writeln!(f, "{INDENT}{}{}", convert_elementdef(elem), comma)?;
//         }
//         writeln!(f, "}}")
//     })
// }

pub fn autogen_csharp_reducer(ctx: &GenCtx, reducer: &ReducerDef) -> String {
    let func_name = reducer.name.as_ref().expect("reducer should have name");
    // let reducer_pascal_name = func_name.to_case(Case::Pascal);
    let use_namespace = true;
    let func_name_pascal_case = func_name.as_ref().to_case(Case::Pascal);

    let mut output = CodeIndenter::new(String::new());

    let mut func_arguments: String = String::new();
    let mut arg_types: String = String::new();
    let mut arg_names: String = String::new();
    let mut arg_event_parse: String = String::new();
    let arg_count = reducer.args.len();

    writeln!(
        output,
        "// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE"
    )
    .unwrap();
    writeln!(output, "// WILL NOT BE SAVED. MODIFY TABLES IN RUST INSTEAD.").unwrap();
    writeln!(output).unwrap();

    writeln!(output, "using System;").unwrap();
    writeln!(output, "using ClientApi;").unwrap();
    writeln!(output, "using Newtonsoft.Json.Linq;").unwrap();

    writeln!(output).unwrap();

    if use_namespace {
        writeln!(output, "namespace {NAMESPACE}").unwrap();
        writeln!(output, "{{").unwrap();
        output.indent(1);
    }

    writeln!(output, "public static partial class Reducer").unwrap();
    writeln!(output, "{{").unwrap();

    {
        indent_scope!(output);

        for (arg_i, arg) in reducer.args.iter().enumerate() {
            let name = arg.name.as_deref().expect("reducer args should have names");
            let arg_name = name.to_case(Case::Camel);
            let arg_type_str = ty_fmt(ctx, &arg.algebraic_type);

            if arg_i > 0 {
                func_arguments.push_str(", ");
                arg_names.push_str(", ");
            }
            arg_event_parse.push_str(", ");
            arg_types.push_str(", ");

            write!(func_arguments, "{} {}", arg_type_str, arg_name).unwrap();

            arg_names.push_str(&arg_name);
            write!(arg_event_parse, "args[{}].ToObject<{}>()", arg_i, arg_type_str).unwrap();

            write!(arg_types, "{}", arg_type_str).unwrap();
        }

        writeln!(
            output,
            "public static event Action<ClientApi.Event.Types.Status, Identity{arg_types}> On{func_name_pascal_case}Event;"
        )
        .unwrap();

        writeln!(output).unwrap();

        writeln!(output, "public static void {func_name_pascal_case}({func_arguments})").unwrap();
        writeln!(output, "{{").unwrap();
        {
            indent_scope!(output);

            //           NetworkManager.instance.InternalCallReducer(new NetworkManager.Message
            // 			{
            // 				fn = "create_new_player",
            // 				args = new object[] { playerId, position },
            // 			});

            // Tell the network manager to send this message
            // UPGRADE FOR LATER
            // write!(output, "{}\t\tNetworkManager.instance.InternalCallReducer(new Websocket.FunctionCall\n", namespace_tab).unwrap();
            // write!(output, "{}\t\t{{\n", namespace_tab).unwrap();
            // write!(output, "{}\t\t\tReducer = \"{}\",\n", namespace_tab, func_name).unwrap();
            // write!(output, "{}\t\t\tArgBytes = Google.Protobuf.ByteString.CopyFrom(Newtonsoft.Json.JsonConvert.SerializeObject(new object[] {{ {} }}), System.Text.Encoding.UTF8),\n", namespace_tab, arg_names).unwrap();
            // write!(output, "{}\t\t}});\n", namespace_tab).unwrap();

            // TEMPORARY OLD FUNCTIONALITY
            writeln!(
                output,
                "NetworkManager.instance.InternalCallReducer(\"{func_name}\", new object[] {{ {arg_names} }});",
            )
            .unwrap();
        }
        // Closing brace for reducer
        writeln!(output, "}}").unwrap();
        writeln!(output).unwrap();

        writeln!(output, "[ReducerEvent(FunctionName = \"{func_name}\")]").unwrap();
        writeln!(
            output,
            "public static void On{func_name_pascal_case}(ClientApi.Event dbEvent)"
        )
        .unwrap();
        writeln!(output, "{{").unwrap();
        {
            indent_scope!(output);

            writeln!(output, "if(On{func_name_pascal_case}Event != null)").unwrap();
            writeln!(output, "{{").unwrap();
            {
                indent_scope!(output);
                writeln!(output, "var jsonString = dbEvent.FunctionCall.ArgBytes.ToStringUtf8();").unwrap();
                writeln!(
                    output,
                    "var args = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(jsonString);"
                )
                .unwrap();

                writeln!(output, "if(args.Count >= {arg_count})").unwrap();
                writeln!(output, "{{").unwrap();
                {
                    indent_scope!(output);
                    writeln!(
                        output,
                        "On{func_name_pascal_case}Event(dbEvent.Status, Identity.From(dbEvent.CallerIdentity.ToByteArray()){arg_event_parse});"
                    )
                    .unwrap();
                }
                // Closing brace for if count is valid
                writeln!(output, "}}").unwrap();
            }
            // Closing brace for if event is registered
            writeln!(output, "}}").unwrap();
        }

        // Closing brace for Event parsing function
        writeln!(output, "}}").unwrap();
    }
    // Closing brace for class
    writeln!(output, "}}").unwrap();

    if use_namespace {
        output.dedent(1);
        writeln!(output, "}}").unwrap();
    }

    output.into_inner()
}