package org.linuxguy.MarketBot;

import com.squareup.okhttp.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class GroupMeNotifier extends Notifier<Comment> implements ResultListener<Comment> {
    private static final String GROUPME_BOT_API = "https://api.groupme.com/v3/bots/post";

    private String mAppName;
    private String mAccessToken;

    public GroupMeNotifier(String appName, String accessToken) {
        mAppName = appName;
        mAccessToken = accessToken;
    }

    @Override
    public void onNewResult(Comment result) {
        try {
            String toPost = getJsonPayloadForComment(result);

            if (!postCommentToGroupMe(toPost)) {
                System.err.println(String.format("Failed to post payload: %s", toPost));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static boolean postCommentToGroupMe(String comment) {
        MediaType urlEncodedMediaType = MediaType.parse("application/json");

        try {
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(urlEncodedMediaType, comment);
            Request request = new Request.Builder()
                                         .url(GROUPME_BOT_API)
                                         .post(body)
                                         .build();

            Response response = client.newCall(request).execute();
            return response.isSuccessful();
        } catch (IOException e) {
            e.printStackTrace();

            return false;
        }
    }

    private String getJsonPayloadForComment(Comment c) throws UnsupportedEncodingException {
        return String.format("{\"text\" : \"%s\", \"bot_id\" : \"%s\"}", formatComment(c), mAccessToken);
    }


    private String formatComment(Comment c) {
        String escapedString = c.text.replace("\"", "\\\"")
                                     .replace("\t", "    ")
                                     .replace("\n", "    ");

        return String.format("%s: \\\"%s\\\"  %s \u2014%s",
                mAppName, escapedString, Utils.formatRatingWithStars(c.rating), c.author);
    }
}

@@ -2108,12 +2108,8 @@
 at(%22
-%25s: 
 %5C%5C%5C%22
@@ -2118,12 +2118,8 @@
 %5C%5C%5C%22
-  %25s
  %5Cu2
@@ -2123,16 +2123,47 @@
 %5Cu2014%25s
+ %25s%5C%5Cn%5C%5Cn%25s v%25s (%25s storefront)
 %22,%0A     
@@ -2176,18 +2176,8 @@
     
- mAppName,
  esc
@@ -2187,16 +2187,26 @@
 dString,
+ c.author,
  Utils.f
@@ -2237,24 +2237,50 @@
 ating), 
-c.author
+mAppName, c.version, c.countryCode
 );%0A    %7D

Improve GroupMe post formatting