package org.jonnyzzz.teamcity.ant;

import jetbrains.buildServer.messages.serviceMessages.ServiceMessage;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Eugene Petrenko (eugene.petrenko@gmail.com)
 *
 */
public class TeamCityServiceMessageTask extends Task {
  @Nullable private String myName = null;
  @Nullable private String myValue = null;
  private final List<KeyValuePart> myArguments = new ArrayList<KeyValuePart>();

  public void setName(@Nullable String name) {
    myName = name;
  }

  public void setValue(@Nullable String value) {
    myValue = value;
  }

  @NotNull
  public KeyValuePart createParam() {
    final KeyValuePart part = new KeyValuePart();
    myArguments.add(part);
    return part;
  }

  @Override
  public void execute() throws BuildException {
    if (myName == null || myName.trim().isEmpty()) {
      throw new BuildException("'name' attribute should be defined");
    }

    if (myValue != null) {
      if (!myArguments.isEmpty()) {
        throw new BuildException("'value' attribute must not co-exist with 'param' sub-elements");
      }

      logServiceMessage(new ServiceMessage(myName, myValue){});
    } else {

      final Map<String, String> paramz = new LinkedHashMap<String, String>();

      for (KeyValuePart arg : myArguments) {
        final String name = arg.getName();
        final String value = arg.getValue();

        if (name == null || name.trim().length() == 0) {
          throw new BuildException("Some 'param' element has no 'name' attribute");
        }

        if (value == null) {
          throw new BuildException("Some 'param' element has no 'value' attribute");
        }

        final String oldValue = paramz.put(name, value);
        if (oldValue != null) {
          throw new BuildException("Multiple values for <param name='" + name + "' ...");
        }
      }

      logServiceMessage(new ServiceMessage(myName, paramz){});
    }
  }

  private void logServiceMessage(@NotNull final ServiceMessage message) {
    final String NL = "\r\n";
    final String text = NL + message.asString() + NL;
    //TODO: may use socket or console output to make sure it's not skipped
    getProject().log(this, text, Project.MSG_WARN);
  }

}


@@ -1364,36 +1364,32 @@
 gServiceMessage(
-new 
 ServiceMessage(m
@@ -1378,32 +1378,41 @@
 e(ServiceMessage
+.asString
 (myName, myValue
@@ -1412,18 +1412,16 @@
 myValue)
-%7B%7D
 );%0A    %7D
@@ -2141,20 +2141,16 @@
 Message(
-new 
 ServiceM
@@ -2155,16 +2155,25 @@
 eMessage
+.asString
 (myName,
@@ -2184,10 +2184,8 @@
 amz)
-%7B%7D
 );%0A 
@@ -2243,29 +2243,21 @@
  final S
-erviceMessage
+tring
  message
@@ -2330,19 +2330,8 @@
 sage
-.asString()
  + N

use utility method, not inherited class