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
package Torello.Browser;

import Torello.JavaDoc.Annotations.LinkJavaSource;
import Torello.JavaDoc.Annotations.IntoHTMLTable;
import static Torello.JavaDoc.Annotations.IntoHTMLTable.Background.BlueDither;
import static Torello.JavaDoc.Annotations.IntoHTMLTable.Background.GreenDither;

import Torello.Java.StrCSV;
import Torello.Java.StrIndent;

import javax.json.JsonObject;

/**
 * An abstract base class for builder-style objects that collect named assignments
 * before producing a final CDP-related object.
 * 
 * <BR /><BR />
 * This class provides the common assignment machinery used by both {@link TypeBuilder}
 * and {@link CommandBuilder}.  Each assignment is checked against an
 * {@link AbstractDescriptor}, which supplies the valid names and expected CDP type
 * information for the builder.
 * 
 * <BR /><BR /><DIV CLASS=JDHint>
 * 📌 Concrete subclasses decide what {@link #build()} produces.  A {@link TypeBuilder}
 * produces a CDP data object, while a {@link CommandBuilder} produces a
 * {@link Script} that may be invoked against the browser.
 * </DIV> 
 * 
 * @param <T> The type produced by this builder's {@link #build()} method.
 *
 * @see TypeBuilder
 * @see CommandBuilder
 * @see AbstractDescriptor
 */
public abstract class AbstractBuilder<T>
    implements java.io.Serializable, Cloneable
{
    // ********************************************************************************************
    // ********************************************************************************************
    // Fields
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS='external-html' DATA-FILE-ID=SVUID> */
    protected static final long serialVersionUID = 1L;

    /**
     * The descriptor used by this builder.  It provides the names, expected types, and ordering
     * for each named assignment accepted by this builder.
     * 
     * <BR /><BR /><DIV CLASS=JDHint>
     * 👉 For {@link TypeBuilder}, these names correspond to fields in a CDP data type.  For
     * {@link CommandBuilder}, they correspond to input parameters for a CDP command.
     * </DIV>
     */
    public final AbstractDescriptor descriptor;

    // Chat-GPT says:
    // 
    // No. Do NOT initialize them manually. Java already guarantees this completely and absolutely.
    // I forget how this works all the time...
    // 
    // already produces:
    //      * every assignments[i] == null
    //      * every assigned[i] == false

    // The values being assigned to the builder
    final Object[] assignments;

    // Because 'null' is a legitimate value, this array is needed.
    final boolean[] assigned;


    // ********************************************************************************************
    // ********************************************************************************************
    // (PRIMARY PURPOSE of this class)
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Convert 'this' Builder-Instance into an actual Object-Instance 
     * @return An instance of {@code T}
     */
    public abstract T build();


    // ********************************************************************************************
    // ********************************************************************************************
    // Constructors & Static "Create a new Builder-Instance" Method
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Protected constructor used by the two {@code AbstractBuilder} subclasses.
     * @param descriptor The descriptor for the class or object which is ultimately being built
     * 
     * @see NestedDescriptor 
     * @see NestedHelper#descriptor()
     * @see CommandDescriptor
     */
    protected AbstractBuilder(final AbstractDescriptor descriptor)
    {
        this.descriptor     = descriptor;
        this.assignments    = new Object[descriptor.size];
        this.assigned       = new boolean[descriptor.size];
    }

    /**
     * Protected constructor used by the {@code 'clone()'} method, inside the two concrete 
     * subclasses of this type.
     * 
     * @param other Another instance of this class
     */
    protected AbstractBuilder(final AbstractBuilder<T> other)
    {
        this.descriptor     = other.descriptor;
        this.assignments    = other.assignments.clone();
        this.assigned       = other.assigned.clone();
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // The Primary / General Purpose Accept-Method
    // ********************************************************************************************
    // ********************************************************************************************


    // The internally used 'accept()' method, invoked by all the other accept methods in this class
    private AbstractBuilder<T> accept(
            final String    name,
            final Object    value,
            final byte      providedType
        )
    {
        final int index = descriptor.names.indexOf(name);

        if (index < 0) throw new AssignmentNameException(name, this.descriptor);

        final byte expectedType = descriptor.types.get(index);

        if (providedType != expectedType) throw new TypeAssignmentException
            (providedType, expectedType, name, this.descriptor);

        if ((expectedType == CDPTypes.CDP_TYPE) || (expectedType == CDPTypes.CDP_TYPE_ARRAY_1D))
            descriptor.checkValueType(value, index);

        assignments[index]  = value;
        assigned[index]     = true;

        return this;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Accept-Methods: CDP Types 
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS=external-html DATA-PARAM=bt DATA-TYPE='BaseType<?>' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a CDP Class (extends BaseType<>) to a Builder Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final BaseType<?> bt)
    { return accept(name, bt, CDPTypes.CDP_TYPE); }

    /** <EMBED CLASS=external-html DATA-PARAM=btArr DATA-TYPE='BaseType[]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign an Array of BaseType<?> (any CDP Class) to a Builder Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final BaseType<?>[] btArr)
    { return accept(name, btArr, CDPTypes.CDP_TYPE_ARRAY_1D); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Accept-Methods: Standard Java Types
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS=external-html DATA-PARAM=i DATA-TYPE='int' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign an 'int' Primitive to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> acceptInt(final String name, final int i)
    { return accept(name, i, CDPTypes.PRIMITIVE_INT); }

    /** <EMBED CLASS=external-html DATA-PARAM=i DATA-TYPE='Integer' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a java.lang.Integer to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final Integer i)
    { return accept(name, i, CDPTypes.BOXED_INTEGER); }

    /** <EMBED CLASS=external-html DATA-PARAM=b DATA-TYPE='boolean' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a 'boolean' primitive to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> acceptBool(final String name, final boolean b)
    { return accept(name, b, CDPTypes.PRIMITIVE_BOOLEAN); }

    /** <EMBED CLASS=external-html DATA-PARAM=b DATA-TYPE='Boolean' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a java.lang.Boolean to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final Boolean b)
    { return accept(name, b, CDPTypes.BOXED_BOOLEAN); }

    /** <EMBED CLASS=external-html DATA-PARAM=s DATA-TYPE='String' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a String to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final String s)
    { return accept(name, s, CDPTypes.STRING); }

    /** <EMBED CLASS=external-html DATA-PARAM=n DATA-TYPE='Number' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a java.lang.Number to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> acceptNumber(final String name, final Number n)
    { return accept(name, n, CDPTypes.NUMBER); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Accept-Methods: One Dimensional Array Types
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS=external-html DATA-PARAM=arr1D DATA-TYPE='int[]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign an int[]-Array to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final int[] arr1D)
    { return accept(name, arr1D, CDPTypes.INT_ARRAY_1D); }

    /** <EMBED CLASS=external-html DATA-PARAM=arr1D DATA-TYPE='boolean[]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a boolean[]-Array to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final boolean[] arr1D)
    { return accept(name, arr1D, CDPTypes.BOOLEAN_ARRAY_1D); }

    /** <EMBED CLASS=external-html DATA-PARAM=arr1D DATA-TYPE='String[]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a String[]-Array to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final String[] arr1D)
    { return accept(name, arr1D, CDPTypes.STRING_ARRAY_1D); }

    /** <EMBED CLASS=external-html DATA-PARAM=arr1D DATA-TYPE='Number[]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a Number[]-Array to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final Number[] arr1D)
    { return accept(name, arr1D, CDPTypes.NUMBER_ARRAY_1D); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Accept-Methods: Two Dimensional Array Types
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS=external-html DATA-PARAM=arr2D DATA-TYPE='int[][]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a Two Dimensional int[][]-Array to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final int[][] arr2D)
    { return accept(name, arr2D, CDPTypes.INT_ARRAY_2D); }

    /** <EMBED CLASS=external-html DATA-PARAM=arr2D DATA-TYPE='boolean[][]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a Two Dimensional boolean[][]-Array to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final boolean[][] arr2D)
    { return accept(name, arr2D, CDPTypes.BOOLEAN_ARRAY_2D); }

    /** <EMBED CLASS=external-html DATA-PARAM=arr2D DATA-TYPE='String[][]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a Two Dimensional String[][]-Array to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final String[][] arr2D)
    { return accept(name, arr2D, CDPTypes.STRING_ARRAY_2D); }

    /** <EMBED CLASS=external-html DATA-PARAM=arr2D DATA-TYPE='Number[][]' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a Two Dimensional java.lang.Number[][]-Array to a Named Builder-Input",
        background=GreenDither
    )
    public AbstractBuilder<T> accept(final String name, final Number[][] arr2D)
    { return accept(name, arr2D, CDPTypes.NUMBER_ARRAY_2D); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Unknown, Raw JSON
    // ********************************************************************************************
    // ********************************************************************************************


    /** <EMBED CLASS=external-html DATA-PARAM=jo DATA-TYPE='JsonObject' DATA-FILE-ID=AB.IHT> */
    @IntoHTMLTable(
        title="Assign a Raw JsonObject to a Named Builder-Input",
        background=BlueDither
    )
    public AbstractBuilder<T> accept(final String name, final JsonObject jo)
    { return accept(name, jo, CDPTypes.RAW_JSON_VALUE); }


    // ********************************************************************************************
    // ********************************************************************************************
    // MISC
    // ********************************************************************************************
    // ********************************************************************************************



    /**
     * Explicitly assigns {@code null} to a Named Builder-Input.
     * 
     * <BR /><BR /><DIV CLASS=JDHint>
     * 🤷 If there is ever a need to ensure that an object property found in a {@link JsonObject}
     * that is being transmitted over a web socket (and towards a browser) has an actual
     * {@link javax.json.JsonValue#NULL Json-Null} intentionally assigned to it, then invoking this
     * method should be utilized.
     * 
     * 🧠 This method guarantees that the internal {@code isPresent} boolean list is assigned 
     * {@code TRUE}, despite the fact that its value is still null.
     * </DIV>
     * 
     * @param name The name of the Builder-Input to which {@code null} shall be assigned.
     * @return {@code 'this'} instance for invocation chaining
     * 
     * @throws AssignmentNameException if {@code 'name'} is not listed by this builder's
     * descriptor.
     * 
     * @see NestedDescriptor#names
     */
    public AbstractBuilder<T> acceptNull(final String name)
    {
        final int index = this.descriptor.names.indexOf(name);

        if (index < 0) throw new AssignmentNameException(name, this.descriptor);

        assignments[index]  = null;
        assigned[index]     = true;

        return this;
    }

    /**
     * Clears any value which may or may not have been assigned to a Named Builder-Input.
     * 
     * @param name The name of the Builder-Input that the programmer would like cleared.
     * @return {@code 'this'} instance for invocation chaining
     * 
     * @throws AssignmentNameException if {@code 'name'} is not listed by this builder's descriptor.
     * 
     * @see AbstractDescriptor#names
     */
    public AbstractBuilder<T> clear(final String name)
    {
        final int index = this.descriptor.names.indexOf(name);

        if (index < 0) throw new AssignmentNameException(name, this.descriptor);

        assignments[index]  = null;
        assigned[index]     = false;

        return this;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // java.lang.Object
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Generate an insightful String representation of {@code 'this'} instance
     * <EMBED CLASS='external-html' DATA-JDHC=JDHint DATA-FILE-ID=AbstractFinalMethod>
     * @return A Java {@code String}
     */
    @Override
    public final String toString()
    { return CDPToString.toString(this); }

    /**
     * Check whether {@code 'this'} instance is equal to input parameter {@code 'o'}
     * 
     * <EMBED CLASS='external-html' DATA-JDHC=JDHint DATA-FILE-ID=AbstractFinalMethod>
     * 
     * @param o Any Java Object.  Only another builder instance of the exact same runtime class,
     * with the same descriptor and current assignment values, will return {@code TRUE}.
     * 
     * @return {@code TRUE} if and only if {@code 'this'} is equal to {@code 'o'}.
     */
    @Override
    public final boolean equals(final Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final AbstractBuilder<?> that = (AbstractBuilder<?>) o;

        return
                this.descriptor.equals(that.descriptor)
            &&  java.util.Arrays.equals(this.assignments, that.assignments)
            &&  java.util.Arrays.equals(this.assigned, that.assigned);
    }

    
    /**
     * Generate a hashcode integer which may be used for placing this object into a hashtable
     * data structure.
     * 
     * <EMBED CLASS='external-html' DATA-JDHC=JDHint DATA-FILE-ID=AbstractFinalMethod>
     * 
     * @return A (hopefully unique) integer value
     */
    @Override
    public final int hashCode()
    {
        int result = this.descriptor.hashCode();
        result = 31 * result + java.util.Arrays.hashCode(this.assignments);
        return result;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // java.lang.Cloneable
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Clone the current instance
     * 
     * @return An identical copy of {@code 'this'}.
     * 
     * <BR /><BR /><DIV CLASS=JDHintAlt>
     * 🔍 The concept known as a "Deep Clone" means that the internals of a type are also
     * copied to the new instance.  What is returned by this method is a "Partial Deep Clone" of
     * {@code 'this'} instance.
     * 
     * <BR /><BR />
     * 🧠 Since the internal {@code 'descriptor'} instance is a read only, singleton instance,
     * cloning it wouldn't have any real significance.  Thus, the internal {@code 'descriptor'}
     * isn't cloned into the new instance; its reference is merely copied instead.
     * 
     * <BR /><BR />
     * 🎯 However, the two internal value-assignment arrays are cloned, resulting in a separate
     * instance which has its own, independent assignments.
     * </DIV>
     */
    @Override
    public abstract AbstractBuilder<T> clone();

}