package com.noa.realtime;

import android.util.Log;

import com.github.kevinsawicki.http.HttpRequest;
import com.tylerjroach.eventsource.EventSource;
import com.tylerjroach.eventsource.EventSourceHandler;
import com.tylerjroach.eventsource.MessageEvent;


/**
 * Created by Noa on 30/10/2017.
 */

public class Api{

    private final EventSource eventSource;
    private SSEHandler sseHandler;
    String endpoint;

    public Api(Manager manager) {

        this.sseHandler = new SSEHandler(manager);
        this.endpoint = "http://vps.guern.eu:8084";

        eventSource = new EventSource.Builder(this.endpoint+"/sse")
            .eventHandler(this.sseHandler)
            .build();
        eventSource.connect();
    }

    public String fetch(String method, String url, String param) {

        String response;

        switch (method) {

            case "GET":
                response = HttpRequest.get(this.endpoint+url).body();
                break;
            case "POST":
                response = HttpRequest.post(this.endpoint+url)
                        .header(HttpRequest.HEADER_CONTENT_TYPE, HttpRequest.CONTENT_TYPE_JSON)
                        .acceptJson()
                        .send(param).body();
                break;
            case "DELETE":
                response = HttpRequest.delete(this.endpoint+url).body();
                break;
            default:
                response = "";
                break;
        }

        return response;
    }
}


/**
 * All callbacks are currently returned on executor thread.
 * If you want to update the ui from a callback, make sure to post to main thread
 */

class SSEHandler implements EventSourceHandler {


    private Manager manager;

    public SSEHandler(Manager manager) {

        this.manager = manager;
    }

    @Override
    public void onConnect() {
        Log.v("SSE Connected", "True");
    }

    @Override
    public void onMessage(String event, MessageEvent message) {
//        Log.v("SSE Message", event);
//        Log.v("SSE Message: ", message.lastEventId);
//        Log.v("SSE Message: ", message.data);

        switch (event) {
            case "add":
                this.manager.addCircleToDrawableList(message.data);
                break;
            case "delete":
                this.manager.removeCircleFromDrawableList(message.data);
                break;
            default:
                break;
        }
    }

    @Override
    public void onComment(String comment) {
        //comments only received if exposeComments turned on
        Log.v("SSE Comment", comment);
    }

    @Override
    public void onError(Throwable t) {
        //ignore ssl NPE on eventSource.close()
    }

    @Override
    public void onClosed(boolean willReconnect) {
        Log.v("SSE Closed", "reconnect? " + willReconnect);
    }
}