/**
 * Copyright (c) 2009-2015, rultor.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met: 1) Redistributions of source code must retain the above
 * copyright notice, this list of conditions and the following
 * disclaimer. 2) Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution. 3) Neither the name of the rultor.com nor
 * the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.rultor.agents;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.jcabi.xml.XML;
import com.rultor.spi.SuperAgent;
import com.rultor.spi.Talk;
import com.rultor.spi.Talks;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.xembly.Directives;

/**
 * Adds index to all the requests received.
 *
 * @author Krzysztof Krason (Krzysztof.Krason@gmail.com)
 * @version $Id$
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public final class IndexesRequests implements SuperAgent {
    @Override
    public void execute(final Talks talks) throws IOException {
        if (talks == null) {
            return;
        }
        int idx = this.index(talks);
        for (final Talk talk : talks.active()) {
            final XML xml = talk.read();
            final List<XML> requestNodes = xml.nodes("/talk/request");
            final int current = idx + 1;
            final String index = "index";
            if (requestNodes.isEmpty()) {
                talk.modify(new Directives().xpath("/talk").addIf("request")
                        .attr(index, Integer.toString(current))
                        .attr("id", this.generateRequestID()).add("type")
                        .set(index).up().add("args")
                );
                idx = current;
            }
        }
    }

    /**
     * Generates unique request ID value based on a {@link UUID} object.
     *
     * @return Unique request ID value
     */
    private String generateRequestID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * Calculates maximal index value for a {@link Talks} object.
     *
     * @param talks The {@link Talks} object
     * @return The maximal index value
     * @throws IOException if the content of one {@link Talk} object can't be read
     */
    private int index(final Talks talks) throws IOException {
        int index = 0;
        for (final Talk talk : talks.active()) {
            final int idx = this.index(talk);
            if (idx > index) {
                index = idx;
            }
        }
        return index;
    }

    /**
     * Calculates maximal (existing) index value of a {@link Talk} object.
     *
     * @param talk The {@link Talk} object
     * @return The maximal index value
     * @throws IOException if the content of the {@link Talk} object can't be read
     */
    private int index(final Talk talk) throws IOException {
        final Iterable<Integer> indexes = Iterables.transform(
                talk.read()
                .xpath("/talk/archive/log/@index|/talk/request/@index"),
            new Function<String, Integer>() {
                @Override
                public Integer apply(final String input) {
                    return Integer.parseInt(input);
                }
            }
        );
        int index;
        if (indexes.iterator().hasNext()) {
            index = Ordering.natural().max(indexes);
        } else {
            index = 0;
        }
        return index;
    }
}

@@ -1716,34 +1716,8 @@
 ng;%0A
-import com.jcabi.xml.XML;%0A
 impo
@@ -1746,16 +1746,16 @@
 rAgent;%0A
+
 import c
@@ -1835,31 +1835,8 @@
 on;%0A
-import java.util.List;%0A
 impo
@@ -2227,17 +2227,17 @@
  (talks 
-=
+!
 = null) 
@@ -2246,34 +2246,8 @@
     
-        return;%0A        %7D%0A
     
@@ -2279,32 +2279,36 @@
 talks);%0A        
+   
+ 
 for (final Talk 
@@ -2340,116 +2340,8 @@
     
-        final XML xml = talk.read();%0A            final List%3CXML%3E requestNodes = xml.nodes(%22/talk/request%22);%0A
     
@@ -2377,16 +2377,20 @@
 dx + 1;%0A
+    
         
@@ -2439,24 +2439,50 @@
     
-if (requestNodes
+    if (talk.read().nodes(%22/talk/request%22)
 .isE
@@ -2503,24 +2503,28 @@
             
+ 
+   
 talk.modify(
@@ -2592,24 +2592,28 @@
             
+    
 .attr(index,
@@ -2660,24 +2660,28 @@
             
+ 
+   
 .attr(%22id%22, 
@@ -2685,33 +2685,20 @@
 %22, this.
-generateRequestID
+uuid
 ()).add(
@@ -2729,16 +2729,20 @@
         
+    
 .set(ind
@@ -2762,16 +2762,20 @@
 %22args%22)%0A
+    
         
@@ -2801,16 +2801,20 @@
         
+    
 idx = cu
@@ -2820,16 +2820,34 @@
 urrent;%0A
+                %7D%0A
         
@@ -2942,39 +2942,32 @@
 k UUID%7D object.%0A
-     *%0A
      * @return U
@@ -3020,25 +3020,12 @@
 ing 
-generateRequestID
+uuid
 () %7B
@@ -3160,39 +3160,32 @@
  Talks%7D object.%0A
-     *%0A
      * @param ta
@@ -3723,15 +3723,8 @@
 ct.%0A
-     *%0A
     
@@ -4342,24 +4342,24 @@
      );%0A
-
         
 int inde
@@ -4342,32 +4342,38 @@
      );%0A        
+final 
 int index;%0A     

Fix suggested problems in IndexesRequests