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

import Torello.Java.ReadOnly.ReadOnlyList;
import Torello.Java.ReadOnly.ReadOnlyMap;

import java.util.stream.IntStream;

import javax.json.JsonObject; // JavaDoc Needs this
import javax.json.stream.JsonGenerator;

/**
 * This class is declared {@code 'abstract'} and serves as the root ancestor clas for all data 
 * record types &amp; events in all <B STYLE='color:red;'><I>domains</I></B> in within the 
 * Chrome DevTools Protocol (CDP) API.
 * 
 * <BR /><BR />
 * This class utilizes a "Singleton Design Pattern."  Each of the types and events in CDP
 * ({@code 'Torello.Browser.*'}) are declared as nested classes within a parent or "container"
 * class, rather than as standalone types.  This decision helps make clear which types belong to
 * which domains in CDP.
 * 
 * <BR /><BR />
 * Programatically, it would likely be a little bit more "clear" to have a separate Java Package
 * for Google Domain.  In fact, within the Web-Browser Source-Code, a "domain" is essentially 
 * idential to the word "Java Package."  What's the catch?  Owing to the fact that the domains,
 * types &amp; events in the CDP-API (this Java-Wrapper) are nothing more than "Wrapper Code" that
 * sends JSON requests to the browser, and parses responses from the browser.
 * 
 * <BR /><BR /><DIV CLASS=JDHint>
 * Essentially, the classes, methods &amp; types in the Browser &amp; JavaScript API's are just
 * "messengers" to and from Google Chrome.  As such, the actual source code for these "domains"
 * is not in Java, but inside Chrome, itself.  Thusly, compacting all of the types &amp; events
 * into a <B STYLE='color:red'>single Java Class</B> (one class per domain) seems an intelligent 
 * design choice.
 * </DIV>
 * 
 * <BR />
 * Each of the types &amp; in every domain of the CDP uses this abstract class as its root 
 * ancestor.
 * 
 */
public abstract class BaseType<DOMAIN_NESTED extends BaseType<DOMAIN_NESTED>>
    implements Comparable<BaseType<?>>
{
    // Don't ask.  Chat-GPT convinced me this is the "best way" to do this... It is not that 
    // important.  It is just annoying enough to look (at least for me) to warrant / justify this
    // pointless comment.
    // 
    // "THIS" is needed to pass 'this' to each of the helper methods inside of the helper singleton
    // class.  If you look at the one line method bodies for equals, hashCode, toJSON and fromJSON
    // you will see 'THIS' field being used!

    @SuppressWarnings("unchecked")
    private final DOMAIN_NESTED THIS = (DOMAIN_NESTED) this;


    // ********************************************************************************************
    // ********************************************************************************************
    // Constructor
    // ********************************************************************************************
    // ********************************************************************************************


    /** Constructor for this {@code abstract-class} */
    protected BaseType(
            final NestedHelper<DOMAIN_NESTED>   helperSingleton,
            final Domains                       domain,
            final String                        name,
            final int                           numFields
        )
    {
        this.helperSingleton    = helperSingleton;
        this.domain             = domain;
        this.name               = name;
        this.numFields          = numFields;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Instance Fields
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Singleton Instance of the Nested Helper Class.  This is how the "Singleton Design Pattern"
     * is implemented.  The methods &amp; fields in this class implement many of the features 
     * offered by abstract class {@code 'BaseType'}.
     */
    public final NestedHelper<DOMAIN_NESTED> helperSingleton;

    /**
     * It was decided by somebody other than I that there are to be two API's of the browser 
     * Remote-Debug-Port interface.  The two API's were decided to be the {@code JavaScript}
     * API, and the {@code Browser} API.  These two do not have a lot of distinction or meaning.
     * 
     * <BR /><BR />💡 Each API has several categories of methods, and these are called 
     * {@code Domain's}.
     */
    public final Domains domain;

    /**
     * The event has a name, and this name happens to be the exact same name as the
     * event-{@code class} itself.
     */
    public final String name;

    /**
     * This is the number of fields in this class.  It is like a reflection-field reflecting
     * information for the concrete subclass instance.
     */
    public final int numFields;


    /**
     * The {@code 'isPresent'} boolean-array cannot be assigned inside of this abstract ancestor
     * class' constructor.  Thus, the only other option for actually using or retrieving the values
     * in this list is to include a simple {@code 'getter'} or {@code 'accessor'} method.  See
     * method: {@link #isPresent()}
     * 
     * <BR /><BR />
     * The {@code 'isPresent'} list cannot be assigned until after the fields of the concrete 
     * instance sub-class have been assigned.  Since it was not until JDK 22+ that statements 
     * prior to the invocation of {@code super()} were allowed inside of constructors, this field 
     * shall simply remain {@code 'protected'} and inaccessible to outside modification.
     * 
     * @see #isPresent()
     */
    public ReadOnlyList<Boolean> isPresent;



    // ********************************************************************************************
    // ********************************************************************************************
    // java.lang.Object, java.lang.Comparable
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Checks the Contents of this class again the input parameter {@code 'other'} for euality.
     * <EMBED CLASS='external-html' DATA-FILE-ID=BaseType.HelperSingletonNote>
     * @return {@code 'TRUE'} if and only if the two instances are equal.
     * @see NestedHelper#equals(BaseType, Object)
     */
    public final boolean equals(Object other)
    { return helperSingleton.equals(THIS, other); }

    /**
     * Generates a Hash-Code for this class, which may be used for hashing into maps and sets.
     * <EMBED CLASS='external-html' DATA-FILE-ID=BaseType.HelperSingletonNote>
     * @return a valid hash code for this object.
     * @see NestedHelper#hashCode(BaseType)
     */
    public final int hashCode()
    { return helperSingleton.hashCode(THIS); }

    /**
     * This method uses Java Reflection to convert the inheriting object into a {@code String}.
     * @return A {@code java.lang.String} representation of {@code 'this'} object
     */
    public final String toString()
    { return CDPToString.toString(THIS); }

    /**
     * Compares this {@code BaseType} to another for ordering.
     * 
     * <BR /><BR />
     * Comparison is performed in two steps:
     * 
     * <BR /><BR /><OL CLASS=JDOL>
     *     <LI>First by {@code domain}</LI>
     *     <LI>Then by {@code name} if domains are equal</LI>
     * </OL>
     *
     * @param o The {@code BaseType} to be compared.
     *
     * @return A negative integer, zero, or a positive integer as this object is less
     *         than, equal to, or greater than the specified object.
     *
     * @throws NullPointerException If {@code o} is {@code null}.
     */
    @Override
    public final int compareTo(final BaseType<?> o)
    {
        final int i = this.domain.compareTo(o.domain);
        if (i != 0) return i;

        return this.name.compareTo(o.name);
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Json Serialization Method
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Serializes {@code 'this'} object into JSON.
     * 
     * <BR /><BR /><OL CLASS=JDOL>
     * <LI>It is OK if 'name' is null.</LI>
     * <LI>It is NOT-OK if 'jGen' is null.</LI>
     * </OL>
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=BaseType.HelperSingletonNote>
     * 
     * @param name The name being assigned to this {@link JsonObject} Property.  This name may be
     * null.  If null is passed here, the {@link JsonGenerator} will treat this Object as the top
     * level JSON Object, not a property of a larger object.
     * 
     * @param jGen This is the generator instance.  Note that often, when serializing Java Objects
     * to JSON (<I>and vice-versa!</I>), one object may be a property or field of another object.
     * When serializing an object to JSON, if there is a field that also needs to be serialized as
     * a {@code JsonObject}, just pass the name and this generator instance in order to include
     * that field as a sub-property.
     * 
     * @see NestedHelper#toJSON(BaseType, String, JsonGenerator)
     */
    public final void toJSON(final String name, final JsonGenerator jGen)
    { helperSingleton.toJSON(THIS, name, jGen); }


    // ********************************************************************************************
    // ********************************************************************************************
    // Data Validation / Integrity Methods
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Checks whether the state of a type or event is actually valid, according to the CDP
     * specifications, as per the field's "Optional Flag."  Google's Json-Specifications File for
     * the CDP-API declares that some fields (referred to as 'properties' in the CDP-API Json-Spec
     * File) for some of the API's types &amp; events are not actually mandatory or required.  When
     * Google Chrome (or another CDP compliant Web-Browser) returns a type, or fires / generates an
     * event, the browser may choose to omit certain fields in the classes that are constructed and 
     * returned to you, the end user.
     * 
     * <BR /><BR /><DIV ClASS=JDHint>
     * Generally, such fields are assigned null.  <B STYLE='color:red;'>This design choice explains
     * why Java's Boxed-Types (such as {@code java.lang.Integer} may seem ubiquitous in this
     * API</B>).  Note that fields which are declared as simple types such as {@code 'int'} are 
     * indeed declared using a Java Primitive {@code 'int'}, not the boxed type
     * {@code 'java.lang.Integer'}.
     * </DIV>
     * 
     * <BR />There are only two minor issues.  One, Google Chrome is not under "developmental
     * control" of "Torello Software."  Though, theoretically, Chome would never omit a "non
     *  optional property", on the off chance that it has done so, this method can be 
     * used to scan for such an occurence.
     * 
     * <BR /><BR />
     * Since both types and events can be constructed using their respective public constructors,
     * if a user has omitted a field (Google doesn't use the term 'field' or 'class', instead it
     * refers to such concepts as 'types', 'events', and 'properties'), then this method may als 
     * be used to validate user constructed objects.
     * 
     * @return returns an {@code java.util.stream.IntStream} containing all indices of fields which
     * meets these criteria:
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * <LI>hasn't been declared optional in the CDP specifications</LI>
     * <LI>is asserted not to be present, as per the value of {@code 'this'} isPresentList</LI>
     * </UL>
     * 
     * <BR /><BR />If there are no such fields, then this method simply returns an empty
     * {@code java.util.stream.IntStream}.
     * 
     * @see NestedDescriptor#optionals
     * @see #isPresent()
     */
    public final IntStream optionalsValidate()
    {
        final IntStream.Builder     b           = IntStream.builder();
        final ReadOnlyList<Boolean> optionals   = helperSingleton.descriptor().optionals;
        final ReadOnlyList<Boolean> isPresent   = this.isPresent();
        final int                   NUM         = optionals.size();

        for (int i=0; i < NUM; i++)
            if (! optionals.get(i))     // TRUE => 'optional', FALSE => 'mandatory'
                if (!isPresent.get(i))  // TRUE => 'included', FALSE => 'omitted'
                    b.accept(i);

        return b.build();
    }

    /**
     * Generates a properly formatted exception throw message using the output produced by 
     * {@link #optionalsValidate()}, and then throws {@link NullNonOptionalException}.
     * 
     * <BR /><BR /><DIV CLASS=JDHint>
     * If the output {@code IntStream} returned by {@code optionalsValidate} is empty, then this
     * method simply exits, and returns gracefull - WITHOUT THROWING.
     * </DIV>
     * 
     * @throws NullNonOptionalException If the {@code IntStream} returned by
     * {@code optionalsValidate()} has a non-zero length.
     * 
     * @see #optionalsValidate()
     * @see NestedDescriptor#optionals
     * @see #isPresent()
     */
    public void optionalsValidateThrow()
    {
        final int[] errors = optionalsValidate().toArray();

        if (errors.length == 0) return;

        throw new NullNonOptionalException
            (printHelper(errors, "isn't present, but also isn't optional"));
    }

    /**
     * This method will investigate the contents of any &amp; string fields in the concrete 
     * sub-type of {@code 'this'} instance for validity against pre-defined <B STYLE='color:red;'>
     * enumerated string constants</B>. 
     * 
     * <BR /><BR />If {@code 'this'} concrete sub-type doesn't have any string fields among its
     * public fields, or the string fields which it has have not been designted as members of a
     * domain "enum type", then this method returns an empty {@code java.util.stream.IntStream}.
     *
     * <EMBED CLASS='external-html' DATA-FILE-ID=BaseType.HelperSingletonNote>
     * 
     * @return returns an {@code java.util.stream.IntStream} containing all indices of fields which
     * meets these criteria:
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * <LI>is declared as a CDP (or Java) <B STYLE='color:red;'><CODE>String</CODE></B></LI>
     * <LI>has failed to abide by a pre-specified list of enumerated string constants</LI>
     * </UL>
     * 
     * <BR /><BR />If there are no such fields, then this method simply returns an empty
     * {@code java.util.stream.IntStream}.
     * 
     * @see NestedHelper#enumStrValidate(BaseType)
     */
    public final IntStream enumStrValidate()
    { return helperSingleton.enumStrValidate(THIS); }

    /**
     * Generates a properly formatted exception throw message using the output produced by 
     * {@link #optionalsValidate()}, and then throws {@link InvalidEnumStrException}.
     * 
     * <BR /><BR /><DIV CLASS=JDHint>
     * If the output {@code IntStream} returned by {@code enumStrValidate} is empty, then this
     * method simply exits, and returns gracefull - WITHOUT THROWING.
     * </DIV>
     * 
     * @throws InvalidEnumStrException If the {@code IntStream} returned by
     * {@code optionalsValidate()} has a non-zero length.
     * 
     * @see #enumStrValidate()
     * @see NestedHelper#enumStrValidate(BaseType)
     */
    public void enumStrValidateThrow()
    {
        final int[] errors = enumStrValidate().toArray();

        if (errors.length == 0) return;

        throw new InvalidEnumStrException
            (printHelper(errors, "has an invalid string value"));
    }

    private String printHelper(final int[] errors, final String msg)
    {
        final StringBuilder                     sb          = new StringBuilder();
        final NestedDescriptor<DOMAIN_NESTED>   descriptor  = helperSingleton.descriptor();
        final ReadOnlyList<String>              names       = descriptor.names;

        sb.append("In class: " + this.getClass().getSimpleName() + "\n");
        for (final int i : errors)
            sb.append("Field \"" + names.get(i) + "\" " + msg + '\n');

        return sb.toString();
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // More Method(s)
    // ********************************************************************************************
    // ********************************************************************************************


    // This seemingly pointless method is used by "ToString".
    // 
    // Can be eliminated if I ever :
    //  * switch to JDK 21+ which use records and an auto-generated tostring
    //  * write my "To String Generator" classes.  
    // 
    // Right now, I am settling with "BT$ToString," which happens to need this method...
    // Note that the "ugliness" of this method is that there is a static method in each and every
    // subclass or descendant of "BaseType" that also has a method named "descriptor()" which 
    // happens to do the exact same thing as this one...

    NestedDescriptor<DOMAIN_NESTED> getDescriptor() 
    { return helperSingleton.descriptor(); }

    /**
     * Accessor method for the private, internal {@code 'isPresent'} instance field.  This 
     * field cannot be assigned inside of this abstract ancestor class' constructor.  Thus, the 
     * {@code 'isPresent'} field also cannot be declared {@code 'final'}.  As a result, the only
     * other option for actually using or retrieving the values in this list is to include this 
     * simple {@code 'getter'} or {@code 'accessor'} method.
     * 
     * <BR /><BR />This getter shields the internal, non-final field value from modification.
     * 
     * @return The list contained by the {@code 'isPresent'} instace field.
     */
    public final ReadOnlyList<Boolean> isPresent()
    { return this.isPresent; }

    /**
     * Retrieves a {@link ReadOnlyMap} mapping field names to a {@link ReadOnlyList} of valid
     * {@code String} values for each field in the map.
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=BaseType.allEnumStrROLs>
     * @see NestedHelper#allEnumStrROLs()
     * @see #enumStrValidate()
     * @see #enumStrValidateThrow()
     */
    public ReadOnlyMap<String, ReadOnlyList<String>> allEnumStrROLs()
    { return helperSingleton.allEnumStrROLs(); }

    /**
     * Retrieve any associated string-enumeration lists for a given field, if they exist.
     * 
     * @param fieldName The name of any field in this class, as a {@code java.lang.String}
     * 
     * @return A read-only list of strings containing the string-enumeration that restricts the 
     * value of the field / property indicated by {@code 'fieldName'}
     * 
     * <BR /><BR />
     * This method shall return <B><CODE>'null'</CODE></B> if:
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * 
     * <LI>The indicated field is not a {@code String} field or property in the first place</LI>
     * 
     * <LI> The field is a {@code String} property, but isn't restricted by an string-enumeration 
     *      lists, as per the CDP specification-definition files.
     *      </LI>
     * </UL>
     * 
     * @throws UnknownPropertyException If the {@code Class} which defines {@code 'this'} instance
     * does not have the specified field in its class definition.
     * 
     * @see #allEnumStrROLs
     * @see NestedHelper#allEnumStrROLs()
     */
    public ReadOnlyList<String> enumStrList(final String fieldName)
    {
        // If this class doesn't have a field named 'fieldName', then throw.
        if (! helperSingleton.descriptor().names.contains(fieldName)) 
            throw new UnknownPropertyException(fieldName);

        // Returns the list if it exists, and null if this field isn't an enum-restricted field
        return helperSingleton.allEnumStrROLs().get(fieldName);
    }
}