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

import Torello.HTML.helper.AttrRegEx;

import Torello.Java.StringParse;

import java.util.Properties;
import java.util.List;
import java.util.Set;

import java.util.stream.Collectors;
import java.util.regex.Matcher;

class GetSetAttr
{
    static String AV(
            final TagNode   tn, 
            final String    innerTagAttribute,
            final boolean   keepQuotes
        )
    {
        // All HTML element tags that start like: </DIV> with a front-slash.
        // They may not legally contain inner-tag attributes.

        if (tn.isClosing) return null;    

        final String itv = innerTagAttribute.trim();


        // All HTML element tags that contain only <TOK> (TOK <==> Tag-Name) in their 'str' field
        // Specifically: '<', TOKEN, '>',  (Where TOKEN is 'div', 'span', 'table', 'ul', etc...)
        // are TOO SHORT to have the attribute, so don't check... return null.
        // 
        // '4 + tok.length +itv.length'  ==>  '<', ' ', '=', '>'
        //                                      + DIV/SPAN/TABLE.length
        //                                      + CLASS/ID/HREF/AttrName.length
        // 
        // NOTE: This is **ALMOST** identical to "tn.isOpenTagPWA()", except that it adds the
        //       length of 'itv' into the number.

        if (tn.str.length() < (4 + tn.tok.length() + itv.length())) return null;

        // Matches "Attribute / Inner-Tag Key-Value" Pairs.
        Matcher m = AttrRegEx.KEY_VALUE_REGEX.matcher(tn.str);


        // This loop iterates the KEY_VALUE PAIRS THAT HAVE BEEN FOUND.
        /// NOTE: The REGEX Matches on Key-Value Pairs.

        while (m.find())


            // m.group(2) is the "KEY" of the Attribute KEY-VALUE Pair
            // m.group(3) is the "VALUE" of the Attribute.

            if (m.group(2).equalsIgnoreCase(innerTagAttribute))

                return keepQuotes 
                    ? m.group(3)
                    : StringParse.ifQuotesStripQuotes(m.group(3));

        // This means the attribute name provided to parameter 'innerTagAttribute' was not found.
        return null;
    }

    static TagNode setAV(
            final TagNode   tn,
            final String    attribute,
            final String    value,
            final SD        quote
        )
    {
        ClosingTagNodeException.check(tn);

        if (attribute == null) throw new NullPointerException(
            "You have passed 'null' to the 'attribute' (attribute-name) String-parameter, " +
            "but this is not allowed here."
        );

        if (value == null) throw new NullPointerException(
            "You have passed 'null' to the 'attribute' (attribute-value) String-parameter, " +
            "but this is not allowed here."
        );


        // Retrieve all "Key-Only" (Boolean) Attributes from 'this' (the original) TagNode
        // Use Java Streams to filter out any that match the newly-added attribute key-value pair.
        // SAVE: Save the updated / shortened list to a List<String>

        List<String> prunedOriginalKeyOnlyAttributes =
            KeyOnlyAttributes.allKeyOnlyAttributes(tn, true)
                .filter((String originalKeyOnlyAttribute) -> 
                    ! originalKeyOnlyAttribute.equalsIgnoreCase(attribute))
                .collect(Collectors.toList());


        // Retrieve all Inner-Tag Key-Value Pairs.  Preserve the Case of the Attributes.  Preserve
        // the Quotation-Marks.

        Properties  p                       = RetrieveAllAttr.allAV(tn, true, true);
        String      originalValueWithQuotes = null;
        String      computedQuote           = null;


        // NOTE, there should only be ONE instance of an attribute in an HTML element, but
        // malformed HTML happens all the time, so to keep this method safe, it checks
        // (and removes) the entire attribute-list for matches - not just the first found instance.

        for (String key : p.stringPropertyNames())

            if (key.equalsIgnoreCase(attribute))
            {
                Object temp = p.remove(key);
                if (temp instanceof String) originalValueWithQuotes = (String) temp;
            }


        // If the user does not wish to "change" the original quote choice, then find out what
        // the original-quote choice was...

        if (
                (quote == null) 
            &&  (originalValueWithQuotes != null)
            &&  (originalValueWithQuotes.length() >= 2)
        )
        {
            char s = originalValueWithQuotes.charAt(0);
            char e = originalValueWithQuotes.charAt(originalValueWithQuotes.length() - 1);

            if ((s == e) && (s == '\''))        computedQuote = "" + SD.SingleQuotes.quote;

            else if ((s == e) && (s == '"'))    computedQuote = "" + SD.DoubleQuotes.quote;

            else                                computedQuote = "";
        }

        else if (quote == null)                 computedQuote = "";

        else                                    computedQuote = "" + quote.quote;

        p.put(attribute, computedQuote + value + computedQuote);

        /* TagNode ret = */ return Torello.HTML.EXPORT_PORTAL.newTagNode(
            tn.tok,
            GeneralPurpose.generateElementString(
                // Rather than using '.tok' here, preserve the case of the original HTML Element
                tn.str.substring(1, 1 + tn.tok.length()), p,
                prunedOriginalKeyOnlyAttributes, null /* SD */, tn.str.endsWith("/>")
            ));

        /*
        System.out.println(
            "GetSetAttr.setAV.prunedOriginalKeyOnlyAttributes: [" + prunedOriginalKeyOnlyAttributes + "]\n" +
            "GetSetAttr.setAV.Before:                          [" + tn + "]\n" +
            "GetSetAttr.setAV.After:                           [" + ret + "]"
        );

        return ret;
        */
    }

    static TagNode setAV(
            final TagNode       tn,
            final Properties    attributes,
            final SD            defaultQuote
        )
    {
        ClosingTagNodeException.check(tn);

        // Check that this attributes has elements.
        if (attributes.size() == 0) throw new IllegalArgumentException(
            "You have passed an empty java.util.Properties instance to the " +
            "setAV(Properties, SD) method"
        );


        // Retrieve all Inner-Tag Key-Value Pairs.
        //      Preserve: the Case of the Attributes.
        //      Preserve: the Quotation-Marks.

        Properties originalAttributes = RetrieveAllAttr.allAV(tn, true, true);

        // Retrieve all "Key-Only" (Boolean) attributes from the new / update attribute-list
        Set<String> newAttributeKeys = attributes.stringPropertyNames();


        // Retrieve all "Key-Only" (Boolean) Attributes from 'this' (the original) TagNode
        // Use Java Streams to filter out all the ones that need to be clobbered by-virtue-of
        // the fact that they are present in the new / parameter-updated attribute key-value list.
        // SAVE: Save the updated / shortened list to a List<String>

        List<String> prunedOriginalKeyOnlyAttributes =
            KeyOnlyAttributes.allKeyOnlyAttributes(tn, true)
            .filter((String originalKeyOnlyAttribute) ->
            {
                // Returns false when the original key-only attribute matches one of the
                // new attributes being inserted.  Notice that a case-insensitive comparison
                // must be performed - to preserve case.

                for (String newKey : newAttributeKeys) 
                    if (newKey.equalsIgnoreCase(originalKeyOnlyAttribute)) 
                        return false;

                return true;
            })
            .collect(Collectors.toList());


        // NOTE: There is no need to check the validity of the new attributes.  The TagNode
        //       constructor that is invoked on the last line of this method will do a 
        //       validity-check on the attribute key-names provided to the 'attributes' 
        //       java.util.Properties instance passed to to this method.

        for (String newKey : newAttributeKeys)
        {
            String      originalValueWithQuotes = null;
            String      computedQuote           = null;


            // NOTE, there should only be ONE instance of an attribute in an HTML element, but
            // malformed HTML happens all the time, so to keep this method safe, it checks (and
            // removes) the entire attribute-list for matches - not just the first found instance.

            for (String originalKey : originalAttributes.stringPropertyNames())

                if (originalKey.equalsIgnoreCase(newKey))
                {
                    // Remove the original key-value inner-tag pair.
                    Object temp = originalAttributes.remove(originalKey);
                    if (temp instanceof String) originalValueWithQuotes = (String) temp;
                }


            // If the user does not wish to "change" the original quote choice, then find out what
            // the original-quote choice was...

            if (
                    (defaultQuote == null) 
                &&  (originalValueWithQuotes != null)
                &&  (originalValueWithQuotes.length() >= 2)
            )
            {
                char s = originalValueWithQuotes.charAt(0);
                char e = originalValueWithQuotes.charAt(originalValueWithQuotes.length() - 1);

                if ((s == e) && (s == '\''))        computedQuote = "" + SD.SingleQuotes.quote;

                else if ((s == e) && (s == '"'))    computedQuote = "" + SD.DoubleQuotes.quote;

                else                                computedQuote = "";
            }

            else if (defaultQuote == null)          computedQuote = "";

            else                                    computedQuote = "" + defaultQuote.quote;


            // Insert the newly, updated key-value inner-tag pair.  This 'Properties' will be
            // used to construct a new TagNode.

            originalAttributes.put(newKey, computedQuote + attributes.get(newKey) + computedQuote);
        }

        return Torello.HTML.EXPORT_PORTAL.newTagNode(
            tn.tok,
            GeneralPurpose.generateElementString(
                // Rather than using '.tok' here, preserve the case of the original HTML Element
                tn.str.substring(1, 1 + tn.tok.length()),
                originalAttributes,
                prunedOriginalKeyOnlyAttributes, null /* SD */,
                tn.str.endsWith("/>")
            ));
    }

    static TagNode appendToAV(
            final TagNode   tn,
            final String    attribute,
            final String    appendStr,
            final boolean   startOrEnd,
            final SD        quote
        )
    {
        ClosingTagNodeException.check(tn);

        if (attribute == null) throw new NullPointerException(
            "You have passed 'null' to the 'attribute' (attribute-name) String-parameter, " +
            "but this is not allowed here."
        );

        if (appendStr == null) throw new NullPointerException(
            "You have passed 'null' to the 'appendStr' (attribute-value-append-string) " +
            "String-parameter, but this is not allowed here."
        );

        String curVal = GetSetAttr.AV(tn, attribute, false);

        if (curVal == null) curVal = "";


        // This decides whether to insert the "appendStr" before the current value-string,
        // or afterwards.  This is based on the passed boolean-parameter 'startOrEnd'

        curVal = startOrEnd ? (appendStr + curVal) : (curVal + appendStr);

        /*
        TagNode ret = setAV(tn, attribute, curVal, quote);

        System.out.println(
            "GetSetAttr.appendToAV.curVal: [" + curVal + "]\n" +
            "GetSetAttr.appendToAV.Before: [" + tn + "]\n" +
            "GetSetAttr.appendToAV.After:  [" + ret + "]"
        );

        return ret;
        */

        // Reuse the 'setAV(String, String, SD)' method already defined in this class.
        return setAV(tn, attribute, curVal, quote);
    }   
}