package sb.tasks.notif.telegram;

import com.jcabi.http.Request;
import com.jcabi.log.Logger;
import org.cactoos.collection.Joined;
import org.cactoos.list.ListOf;
import org.cactoos.scalar.Ternary;
import org.cactoos.scalar.UncheckedScalar;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

public final class CurlBotAnswer implements TgAnswer {

    private final TgAnswer origin;
    private final Properties props;

    public CurlBotAnswer(Properties props, TgAnswer origin) {
        this.origin = origin;
        this.props = props;
    }

    @Override
    public Request request(String chatId, String text) {
        return this.origin.request(chatId, text);
    }

    @Override
    public void send(String chatId, String text) {
        try {
            List<String> cmd = new CurlCmd()
                    .fromRequest(
                            this.origin.request(chatId, text)
                    );
            Logger.info(this, "#send [%s]", cmd);
            new ProcessBuilder(cmd)
                    .start()
                    .waitFor();
        } catch (InterruptedException | IOException ex) {
            Logger.info(this, "%s", ex);
        }
    }

    private final class CurlCmd {

        public List<String> fromRequest(Request request) {
            return new ListOf<>(
                    new Joined<>(
                            new ListOf<>(
                                    "/usr/bin/curl",
                                    "--retry", "5",
                                    String.format("\"%s\"", request.uri())
                            ),
                            new UncheckedScalar<>(
                                    new Ternary<List<String>>(
                                            () -> props.containsKey("curl.extra-opts")
                                                    && !props.getProperty("curl.extra-opts", "").isEmpty(),
                                            () -> new ListOf<>(
                                                    props.getProperty("curl.extra-opts").split("\\s+")
                                            ),
                                            ListOf<String>::new
                                    )
                            ).value()
                    )
            );
        }
    }
}

@@ -947,58 +947,8 @@
  );%0A
-            Logger.info(this, %22#send %5B%25s%5D%22, cmd);%0A
     
@@ -979,16 +979,16 @@
 er(cmd)%0A
+
         
@@ -1040,16 +1040,66 @@
 tFor();%0A
+            Logger.info(this, %22#send %5B%25s%5D%22, cmd);%0A
         
@@ -1167,28 +1167,28 @@
  Logger.
-info
+warn
 (this, %22
 %25s%22, ex)
@@ -1179,16 +1179,22 @@
 (this, %22
+#send 
 %25s%22, ex)
@@ -1575,14 +1575,10 @@
 at(%22
-%5C%22%25s%5C%22
+%25s
 %22, r

fix curl args