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
use crate::io::RenderKotlin;
use crate::spec::{VisibilityModifier, Argument, ClassInheritanceModifier, CodeBlock, CompanionObject, Function, GenericParameter, Name, PrimaryConstructor, Property, SecondaryConstructor, Type, Annotation};
use crate::spec::annotation::{mixin_annotation_mutators, AnnotationSlot};
use crate::spec::kdoc::{KdocSlot, mixin_kdoc_mutators};
use crate::tokens;

#[derive(Debug, Clone)]
pub(crate) enum ClassMemberNode {
    Property(Property),
    Function(Function),
    Subclass(Class),
    SecondaryConstructor(SecondaryConstructor),
    InitBlock(CodeBlock),
}

impl RenderKotlin for ClassMemberNode {
    fn render_into(&self, block: &mut CodeBlock) {
        match self {
            ClassMemberNode::Property(property) => {
                block.push_renderable(property);
            }
            ClassMemberNode::Function(function) => {
                block.push_renderable(function);
            }
            ClassMemberNode::Subclass(subclass) => {
                block.push_renderable(subclass);
            }
            ClassMemberNode::SecondaryConstructor(secondary_constructor) => {
                block.push_renderable(secondary_constructor);
            }
            ClassMemberNode::InitBlock(code) => {
                block.push_static_atom(tokens::keyword::INIT);
                block.push_curly_brackets(|block| {
                    block.push_renderable(code);
                });
            }
        }
    }
}

#[derive(Debug, Clone)]
struct EnumInstance {
    name: Name,
    arguments: Vec<Argument>,
}

/// Defines Kotlin's class like entity. This could represent any 'flavour' of class: enum, interface, e.t.c.
/// To change type of class please use [Class::inheritance_modifier].
///
/// #Example
///
/// ## Simple class
/// ```
/// use kotlin_poet_rs::io::RenderKotlin;
/// use kotlin_poet_rs::spec::{Class, Name};
///
/// let class = Class::new(Name::from("Person"));
///
///  assert_eq!(class.render_string(), "public final class Person {\n\n}");
/// ```
///
/// ## Interface
/// ```
/// use kotlin_poet_rs::io::RenderKotlin;
/// use kotlin_poet_rs::spec::{Class, ClassInheritanceModifier, Name};
///
/// let class = Class::new(Name::from("Person"))
///     .inheritance_modifier(ClassInheritanceModifier::Interface);
///
///  assert_eq!(class.render_string(), "public interface Person {\n\n}");
/// ```
#[derive(Debug, Clone)]
pub struct Class {
    name: Name,
    visibility_modifier: VisibilityModifier,
    inheritance_modifier: ClassInheritanceModifier,
    member_nodes: Vec<ClassMemberNode>,
    enum_instances: Vec<EnumInstance>,
    primary_constructor: Option<PrimaryConstructor>,
    companion_object: Option<CompanionObject>,
    generic_parameters: Vec<GenericParameter>,
    parent_classes: Vec<Type>,
    is_inner: bool,
    annotation_slot: AnnotationSlot,
    kdoc: KdocSlot,
}

impl Class {
    /// Creates new plain final class.
    pub fn new<NameLike: Into<Name>>(name: NameLike) -> Self {
        Class {
            name: name.into(),
            visibility_modifier: VisibilityModifier::default(),
            inheritance_modifier: ClassInheritanceModifier::default(),
            member_nodes: Vec::default(),
            enum_instances: Vec::default(),
            primary_constructor: None,
            companion_object: None,
            generic_parameters: Vec::default(),
            parent_classes: Vec::default(),
            is_inner: false,
            annotation_slot: AnnotationSlot::vertical(),
            kdoc: KdocSlot::default(),
        }
    }

    /// Marks class as inner
    pub fn inner(mut self, flag: bool) -> Self {
        self.is_inner = flag;
        self
    }

    /// Set's class visibility modifier
    pub fn visibility_modifier(mut self, visibility_modifier: VisibilityModifier) -> Self {
        self.visibility_modifier = visibility_modifier;
        self
    }

    /// Changes class type
    pub fn inheritance_modifier(mut self, inheritance_modifier: ClassInheritanceModifier) -> Self {
        self.inheritance_modifier = inheritance_modifier;
        self
    }

    /// Adds property to this class. Properties in body will appear in order this method is called.
    pub fn property(mut self, property: Property) -> Self {
        self.member_nodes.push(ClassMemberNode::Property(property));
        self
    }

    /// Adds function to this class. Functions in body will appear in order this method is called.
    pub fn function(mut self, function: Function) -> Self {
        self.member_nodes.push(ClassMemberNode::Function(function));
        self
    }

    /// Adds subclass to this class. Subclasses in body will appear in order this method is called.
    pub fn subclass(mut self, subclass: Class) -> Self {
        self.member_nodes.push(ClassMemberNode::Subclass(subclass));
        self
    }

    /// Adds enum instance to this class. Enum instances in body will appear in order this method is called.
    /// This method is only valid for enum classes. To change class type to enum please use [Class::inheritance_modifier].
    pub fn enum_instance<NameLike: Into<Name>>(mut self, name: NameLike, arguments: Vec<Argument>) -> Self {
        self.enum_instances.push(EnumInstance {
            name: name.into(),
            arguments,
        });
        self
    }

    /// Adds primary constructor to this class.
    pub fn primary_constructor(mut self, primary_constructor: PrimaryConstructor) -> Self {
        self.primary_constructor = Some(primary_constructor);
        self
    }

    /// Adds secondary constructor to this class. Secondary constructors in body will appear in order this method is called.
    pub fn secondary_constructor(mut self, secondary_constructor: SecondaryConstructor) -> Self {
        self.member_nodes.push(ClassMemberNode::SecondaryConstructor(secondary_constructor));
        self
    }

    /// Adds init block to this class. Init blocks in body will appear in order this method is called.
    pub fn init<CodeBlockLike: Into<CodeBlock>>(mut self, block: CodeBlockLike) -> Self {
        self.member_nodes.push(ClassMemberNode::InitBlock(block.into()));
        self
    }

    /// Adds companion object to this class.
    pub fn companion_object(mut self, companion_object: CompanionObject) -> Self {
        self.companion_object = Some(companion_object);
        self
    }

    /// Adds [GenericParameter] to this class.
    /// Could be called multiple times to have multiple generic parameters.
    pub fn generic_parameter(mut self, generic_parameter: GenericParameter) -> Self {
        self.generic_parameters.push(generic_parameter);
        self
    }

    /// Adds parent class / interface to this class.
    pub fn inherits<TypeLike: Into<Type>>(mut self, parent_type: TypeLike) -> Self {
        self.parent_classes.push(parent_type.into());
        self
    }

    mixin_annotation_mutators!();
    mixin_kdoc_mutators!();
}

impl RenderKotlin for Class {
    fn render_into(&self, block: &mut CodeBlock) {
        block.push_renderable(&self.kdoc);
        block.push_renderable(&self.annotation_slot);

        block.push_renderable(&self.visibility_modifier);
        block.push_space();
        if self.is_inner {
            block.push_static_atom(tokens::keyword::INNER);
            block.push_space();
        }
        block.push_renderable(&self.inheritance_modifier);
        block.push_space();
        if !matches!(
            self.inheritance_modifier,
            ClassInheritanceModifier::Interface |
            ClassInheritanceModifier::Object
        ) {
            block.push_static_atom(tokens::keyword::CLASS);
            block.push_space();
        }
        block.push_renderable(&self.name);
        if !self.generic_parameters.is_empty() {
            block.push_angle_brackets(|code| {
                code.push_comma_separated(
                    &self.generic_parameters.iter().map(|it| it.render_definition())
                        .collect::<Vec<CodeBlock>>()
                );
            });
        }
        block.push_space();

        if let Some(primary_constructor) = &self.primary_constructor {
            block.push_renderable(primary_constructor);
            block.push_space();
        }

        if !self.parent_classes.is_empty() {
            block.pop_space();
            block.push_static_atom(tokens::COLON);
            block.push_space();
            block.push_comma_separated(
                &self.parent_classes
            );
            block.push_space();
        }

        block.push_renderable(
            &GenericParameter::render_type_boundaries_vec_if_required(
                &self.generic_parameters
            )
        );

        block.push_curly_brackets(|class_body_code| {
            class_body_code.push_new_line();

            if !self.enum_instances.is_empty() {
                for (inst_idx, instance) in self.enum_instances.iter().enumerate() {
                    class_body_code.push_renderable(&instance.name);
                    class_body_code.push_round_brackets(|arg_code| {
                        arg_code.push_comma_separated(&instance.arguments);
                    });

                    if inst_idx != self.enum_instances.len() - 1 {
                        class_body_code.push_static_atom(tokens::COMMA);
                        class_body_code.push_new_line();
                    }
                }

                class_body_code.push_static_atom(tokens::SEMICOLON);
            }

            for node in &self.member_nodes {
                class_body_code.push_renderable(node);
                class_body_code.push_new_line();
            }

            if let Some(companion_object) = &self.companion_object {
                class_body_code.push_renderable(companion_object);
                class_body_code.push_new_line();
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use crate::spec::{Parameter, GenericInvariance, PropertyGetter, PropertySetter, Type, ClassLikeTypeName, Package, KDoc};
    use super::*;

    #[test]
    fn test_class() {
        let class = Class::new(Name::from("Person"));
        let code = class.render_string();

        assert_eq!(code, "public final class Person {\n\n}");
    }

    #[test]
    fn test_class_with_kdoc() {
        let class = Class::new(Name::from("Person"))
            .kdoc(
                KDoc::from("hello world")
                    .merge(KDoc::from("at here"))
            );
        let code = class.render_string();

        assert_eq!(
            code,
            "/**\n * hello world\n * at here\n */\npublic final class Person {\n\n}"
        );
    }

    #[test]
    fn test_class_with_property() {
        let property = Property::new(
            Name::from("name"),
            Type::string(),
        ).initializer(
            CodeBlock::statement("\"\"")
        ).getter(
            PropertyGetter::new(
                CodeBlock::statement("return field")
            )
        ).setter(
            PropertySetter::new(
                CodeBlock::statement("field = value")
            )
        );

        let class = Class::new(Name::from("Person"))
            .property(property.clone());

        let code = class.render_string();

        assert_eq!(
            code,
            "public final class Person {\n\n    public final var name: kotlin.String = \"\"\n        set(value) {\n            field = value\n        }\n        get() {\n            return field\n        }\n\n}"
        );
    }

    #[test]
    fn test_enum() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Enum)
            .enum_instance(Name::from("Alex"), vec![
                Argument::new_positional(CodeBlock::atom("23"))
            ])
            .enum_instance(Name::from("Vova"), vec![
                Argument::new_positional(CodeBlock::atom("23"))
            ])
            ;
        let code = class.render_string();

        assert_eq!(
            code,
            "public enum class Person {\n\n    Alex(23),\n    Vova(23);}"
        );
    }

    #[test]
    fn test_with_constructor() {
        let class = Class::new(Name::from("Person"))
            .primary_constructor(
                PrimaryConstructor::new()
                    .property(
                        Property::new(
                            Name::from("name"),
                            Type::string(),
                        )
                    )
                    .parameter(
                        Parameter::new(
                            Name::from("age"),
                            Type::int(),
                        )
                    )
            );

        assert_eq!(
            class.render_string(),
            "public final class Person public constructor(public final val name: kotlin.String, age: kotlin.Int) {\n\n}"
        );
    }

    #[test]
    fn test_with_empty_constructor() {
        let class = Class::new(Name::from("Person"))
            .primary_constructor(
                PrimaryConstructor::new()
            );

        assert_eq!(
            class.render_string(),
            "public final class Person public constructor() {\n\n}"
        );
    }

    #[test]
    fn test_with_init_block() {
        let class = Class::new(Name::from("Person"))
            .init(
                CodeBlock::statement("println(42)")
            );

        assert_eq!(
            class.render_string(),
            "public final class Person {\n\n    init{\n        println(42)\n    }\n}"
        );
    }

    #[test]
    fn test_data_class() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Data)
            .primary_constructor(
                PrimaryConstructor::new()
                    .property(
                        Property::new(
                            Name::from("name"),
                            Type::string(),
                        ).initializer(
                            CodeBlock::atom("\"\"")
                        )
                    )
            );

        assert_eq!(
            class.render_string(),
            "public data class Person public constructor(public final val name: kotlin.String = \"\") {\n\n}"
        );
    }

    #[test]
    fn test_data_class_with_secondary_constructor() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Data)
            .primary_constructor(
                PrimaryConstructor::new()
                    .property(
                        Property::new(
                            Name::from("name"),
                            Type::string(),
                        )
                    )
                    .property(
                        Property::new(
                            Name::from("age"),
                            Type::int(),
                        )
                    )
            )
            .secondary_constructor(
                SecondaryConstructor::new()
                    .parameter(
                        Parameter::new(
                            Name::from("name"),
                            Type::string(),
                        )
                    )
                    .delegate_argument(
                        Argument::new_positional(
                            CodeBlock::atom("name")
                        )
                    )
                    .delegate_argument(
                        Argument::new_positional(
                            CodeBlock::atom("23")
                        )
                    )
                    .body(
                        CodeBlock::statement("println(42)")
                    )
            );

        assert_eq!(
            class.render_string(),
            "public data class Person public constructor(public final val name: kotlin.String, public final val age: kotlin.Int) {\n\n    public constructor(name: kotlin.String) : this(name, 23) {\n        println(42)\n    }\n}"
        );
    }

    #[test]
    fn test_interface() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Interface);

        assert_eq!(class.render_string(), "public interface Person {\n\n}");
    }

    #[test]
    fn test_abstract() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Abstract);

        assert_eq!(class.render_string(), "public abstract class Person {\n\n}");
    }

    #[test]
    fn test_object() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Object);

        assert_eq!(class.render_string(), "public object Person {\n\n}");
    }

    #[test]
    fn test_class_with_inner() {
        let class = Class::new(Name::from("Person"))
            .subclass(
                Class::new("InnerPerson")
                    .inheritance_modifier(ClassInheritanceModifier::Abstract)
                    .inner(true)
            );

        assert_eq!(
            class.render_string(),
            "public final class Person {\n\n    public inner abstract class InnerPerson {\n\n    }\n}"
        );
    }

    #[test]
    fn test_sealed() {
        let class = Class::new(Name::from("Person"))
            .inheritance_modifier(ClassInheritanceModifier::Sealed);

        assert_eq!(class.render_string(), "public sealed class Person {\n\n}");
    }

    #[test]
    fn test_generic_class() {
        let class = Class::new(Name::from("Box"))
            .generic_parameter(
                GenericParameter::new(Name::from("A"))
            )
            .generic_parameter(
                GenericParameter::new(Name::from("B"))
                    .invariance(GenericInvariance::In)
            )
            .generic_parameter(
                GenericParameter::new(Name::from("C"))
                    .invariance(GenericInvariance::Out)
            );

        assert_eq!(class.render_string(), "public final class Box<A, in B, out C> {\n\n}");
    }

    #[test]
    fn test_generic_with_parent() {
        let class = Class::new(Name::from("Box"))
            .generic_parameter(
                GenericParameter::new(Name::from("A"))
                    .invariance(GenericInvariance::In)
                    .type_boundary(Type::string())
            )
            .inherits(
                Type::int()
            );

        assert_eq!(
            class.render_string(),
            "public final class Box<in A>: kotlin.Int where A: kotlin.String {\n\n}"
        );
    }

    #[test]
    fn test_generic_class_with_boundaries() {
        let class = Class::new(Name::from("Box"))
            .generic_parameter(
                GenericParameter::new(Name::from("A"))
            )
            .generic_parameter(
                GenericParameter::new(Name::from("B"))
                    .invariance(GenericInvariance::In)
                    .type_boundary(Type::string())
                    .type_boundary(Type::int())
            )
            .generic_parameter(
                GenericParameter::new(Name::from("C"))
                    .invariance(GenericInvariance::Out)
            );

        assert_eq!(class.render_string(), "public final class Box<A, in B, out C> where B: kotlin.String, B: kotlin.Int {\n\n}");
    }

    #[test]
    fn test_with_annotation() {
        let class = Class::new(Name::from("Person"))
            .annotation(
                Annotation::new(ClassLikeTypeName::top_level(
                    Package::from(Vec::new()),
                    Name::from("Deprecated"),
                ))
            );

        assert_eq!(class.render_string(), "@Deprecated()\npublic final class Person {\n\n}");
    }
}