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
use crate::io::RenderKotlin;
use crate::spec::{VisibilityModifier, CodeBlock, MemberInheritanceModifier, Name, Type, Annotation};
use crate::spec::annotation::{mixin_annotation_mutators, AnnotationSlot};
use crate::spec::kdoc::{KdocSlot, mixin_kdoc_mutators};
use crate::tokens;

#[derive(Debug, Clone)]
enum PropertyInitializer {
    Value(CodeBlock),
    Delegate(CodeBlock),
}

impl RenderKotlin for PropertyInitializer {
    fn render_into(&self, block: &mut CodeBlock) {
        match self {
            PropertyInitializer::Value(initializer) => {
                block.push_space();
                block.push_static_atom(tokens::ASSIGN);
                block.push_space();
                block.push_renderable(initializer)
            }
            PropertyInitializer::Delegate(delegate) => {
                block.push_space();
                block.push_static_atom(tokens::keyword::BY);
                block.push_space();
                block.push_renderable(delegate)
            }
        }
    }
}

/// Represents a [Kotlin property](https://kotlinlang.org/docs/properties.html)
#[derive(Debug, Clone)]
pub struct Property {
    name: Name,
    returns: Type,
    inheritance_modifier: MemberInheritanceModifier,
    visibility_modifier: VisibilityModifier,
    initializer: Option<PropertyInitializer>,
    getter: Option<PropertyGetter>,
    setter: Option<PropertySetter>,
    is_mutable: bool,
    is_const: bool,
    is_override: bool,
    annotation_slot: AnnotationSlot,
    kdoc: KdocSlot
}

#[derive(Debug, Clone)]
pub struct PropertyGetter {
    code: CodeBlock,
    annotation_slot: AnnotationSlot
}

impl PropertyGetter {
    pub fn new<CodeBlockLike: Into<CodeBlock>>(code: CodeBlockLike) -> PropertyGetter {
        PropertyGetter {
            code: code.into(),
            annotation_slot: AnnotationSlot::vertical()
        }
    }

    mixin_annotation_mutators!();
}

impl RenderKotlin for PropertyGetter {
    fn render_into(&self, block: &mut CodeBlock) {
        block.push_renderable(&self.annotation_slot);
        block.push_static_atom(tokens::keyword::GET);
        block.push_round_brackets(|_| {});
        block.push_space();
        block.push_static_atom(tokens::CURLY_BRACKET_LEFT);
        block.push_new_line();
        block.push_indent();
        block.push_renderable(&self.code);
        block.push_unindent();
        block.push_static_atom(tokens::CURLY_BRACKET_RIGHT);
        block.push_new_line();
    }
}

#[derive(Debug, Clone)]
pub struct PropertySetter {
    code: CodeBlock,
    visibility_modifier: VisibilityModifier,
    annotation_slot: AnnotationSlot
}

impl PropertySetter {
    pub fn new<CodeBlockLike: Into<CodeBlock>>(code: CodeBlockLike) -> PropertySetter {
        PropertySetter {
            code: code.into(),
            visibility_modifier: VisibilityModifier::default(),
            annotation_slot: AnnotationSlot::vertical()
        }
    }

    pub fn visibility_modifier(mut self, visibility_modifier: VisibilityModifier) -> PropertySetter {
        self.visibility_modifier = visibility_modifier;
        self
    }

    mixin_annotation_mutators!();
}

impl RenderKotlin for PropertySetter {
    fn render_into(&self, block: &mut CodeBlock) {
        block.push_renderable(&self.annotation_slot);
        block.push_static_atom(tokens::keyword::SET);
        block.push_round_brackets(|parameters_code| {
            parameters_code.push_static_atom(tokens::CONV_VAR_VALUE);
        });
        block.push_space();
        block.push_curly_brackets(|set_body| {
            set_body.push_renderable(&self.code);
        });
        block.push_new_line();
    }
}

impl Property {
    pub fn new<NameLike: Into<Name>, TypeLike: Into<Type>>(name: NameLike, returns: TypeLike) -> Property {
        Property {
            name: name.into(),
            returns: returns.into(),
            inheritance_modifier: MemberInheritanceModifier::Final,
            visibility_modifier: VisibilityModifier::default(),
            initializer: None,
            getter: None,
            setter: None,
            is_mutable: false,
            is_const: false,
            is_override: false,
            annotation_slot: AnnotationSlot::vertical(),
            kdoc: KdocSlot::default()
        }
    }

    /// Sets [VisibilityModifier]
    pub fn visibility_modifier(mut self, visibility_modifier: VisibilityModifier) -> Property {
        self.visibility_modifier = visibility_modifier;
        self
    }

    /// Marks function as `override`
    pub fn overrides(mut self, flag: bool) -> Property {
        self.is_override = flag;
        self
    }

    /// Sets [MemberInheritanceModifier]
    pub fn inheritance_modifier(mut self, inheritance_modifier: MemberInheritanceModifier) -> Property {
        self.inheritance_modifier = inheritance_modifier;
        self
    }

    /// Sets property initializer `val some = <initializer>`
    /// Exclusive with [Property::delegate]
    pub fn initializer<CodeBlockLike: Into<CodeBlock>>(mut self, initializer: CodeBlockLike) -> Property {
        self.initializer = Some(PropertyInitializer::Value(initializer.into()));
        self
    }

    /// Sets property delegate `val some by <delegate>`
    /// Exclusive with [Property::initializer]
    pub fn delegate<CodeBlockLike: Into<CodeBlock>>(mut self, delegate: CodeBlockLike) -> Property {
        self.initializer = Some(PropertyInitializer::Delegate(delegate.into()));
        self
    }

    /// Sets [PropertyGetter]
    pub fn getter(mut self, getter: PropertyGetter) -> Property {
        self.getter = Some(getter);
        self
    }

    /// Sets [PropertySetter]
    pub fn setter(mut self, setter: PropertySetter) -> Property {
        self.setter = Some(setter);
        self.is_mutable = true;
        self
    }

    /// Sets property mutability, a.k.a `val` or `var`
    pub fn mutable(mut self, flag: bool) -> Property {
        self.is_mutable = flag;
        self
    }

    /// Adds `const` keyword to property
    pub fn constant(mut self, flag: bool) -> Property {
        self.is_const = flag;
        self
    }

    mixin_annotation_mutators!();
    mixin_kdoc_mutators!();
}

impl RenderKotlin for Property {
    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();
        block.push_renderable(&self.inheritance_modifier);
        block.push_space();

        if self.is_const {
            block.push_static_atom(tokens::keyword::CONST);
            block.push_space()
        }

        if self.is_override {
            block.push_static_atom(tokens::keyword::OVERRIDE);
            block.push_space();
        }

        if self.is_mutable {
            block.push_static_atom(tokens::keyword::VAR);
        } else {
            block.push_static_atom(tokens::keyword::VAL);
        }
        block.push_space();

        block.push_renderable(&self.name);
        block.push_static_atom(tokens::COLON);
        block.push_space();
        block.push_renderable(&self.returns);
        block.push_indent();
        if let Some(initializer) = &self.initializer {
            block.push_renderable(initializer);
        }
        if let Some(setter) = &self.setter {
            block.push_renderable(setter);
        }
        if let Some(getter) = &self.getter {
            block.push_renderable(getter);
        }
        block.push_unindent();
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;
    use crate::spec::ClassLikeTypeName;
    use super::*;

    #[test]
    fn property_render() {
        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 rendered = property.render_string();
        let expected = "public final var name: kotlin.String = \"\"\n    set(value) {\n        field = value\n    }\n    get() {\n        return field\n    }";
        assert_eq!(rendered, expected);
    }

    #[test]
    fn test_constant() {
        let property = Property::new(Name::from("name"), Type::string())
            .constant(true)
            .initializer("\"Alex\"");

        assert_eq!(
            "public final const val name: kotlin.String = \"Alex\"",
            property.render_string()
        )
    }

    #[test]
    fn test_delegate() {
        let property = Property::new(Name::from("name"), Type::string())
            .constant(true)
            .delegate(CodeBlock::atom("lazy { \"Alex\" }"));

        assert_eq!(
            "public final const val name: kotlin.String by lazy { \"Alex\" }",
            property.render_string()
        )
    }

    #[test]
    fn test_override() {
        let property = Property::new(Name::from("age"), Type::int())
            .overrides(true)
            .initializer(CodeBlock::atom("22"));

        assert_eq!(
            "public final override val age: kotlin.Int = 22",
            property.render_string()
        )
    }

    #[test]
    fn test_kdoc() {
        let property = Property::new(Name::from("age"), Type::int())
            .kdoc("Hello\nWorld");

        assert_eq!(
            "/**\n * Hello\n * World\n */\npublic final val age: kotlin.Int",
            property.render_string()
        )
    }

    #[test]
    fn test_annotation() {
        let property = Property::new(Name::from("age"), Type::int())
            .overrides(true)
            .initializer(CodeBlock::atom("22"))
            .annotation(Annotation::new(
                ClassLikeTypeName::from_str("io.github.lexadiky.MyAnnotation")
                    .unwrap()
            ))
            .annotation(Annotation::new(
                ClassLikeTypeName::from_str("io.github.lexadiky.OtherAnnotation")
                    .unwrap()
            ));

        assert_eq!(
            "@io.github.lexadiky.MyAnnotation()\n@io.github.lexadiky.OtherAnnotation()\npublic final override val age: kotlin.Int = 22",
            property.render_string()
        )
    }

    #[test]
    fn test_setter_with_annotation() {
        let setter = PropertySetter::new(CodeBlock::statement("println(47)"))
            .annotation(Annotation::new(
                ClassLikeTypeName::from_str("a.A").unwrap()
            ));

        assert_eq!(
            "@a.A()\nset(value) {\n    println(47)\n}",
            setter.render_string()
        )
    }

    #[test]
    fn test_getter_with_annotation() {
        let setter = PropertyGetter::new(CodeBlock::statement("println(47)"))
            .annotation(Annotation::new(
                ClassLikeTypeName::from_str("a.A").unwrap()
            ));

        assert_eq!(
            "@a.A()\nget() {\n    println(47)\n}",
            setter.render_string()
        )
    }
}