package ch.trvlr.trvlr;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.iid.FirebaseInstanceId;

import org.java_websocket.WebSocket;

import rx.functions.Action1;
import ua.naiksoftware.stomp.LifecycleEvent;
import ua.naiksoftware.stomp.Stomp;
import ua.naiksoftware.stomp.client.StompClient;
import ua.naiksoftware.stomp.client.StompMessage;

import java.util.HashMap;
import java.util.Map;

public class PublicChatActivity extends AppCompatActivity {
    private static final String TAG = "PublicChatActivity";
    private Button sendButton;
    private TextView chatOutput;
    private EditText chatText;
    private StompClient mStompClient;
    private String roomID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_chat);
        sendButton = (Button) findViewById(R.id.sendButton);
        chatOutput = (TextView) findViewById(R.id.chatOutput);
        chatText = (EditText) findViewById(R.id.chatText);
        roomID = "1";

        Map mStompHeaders = new HashMap();
        mStompHeaders.put("token", FirebaseInstanceId.getInstance().getToken().toString());
        Log.d(TAG, FirebaseInstanceId.getInstance().getToken().toString());

        mStompClient = Stomp.over(WebSocket.class, "ws://trvlr.ch:8080/socket", mStompHeaders);

        mStompClient.lifecycle().subscribe(new Action1<LifecycleEvent>() {
            @Override
            public void call(LifecycleEvent lifecycleEvent) {
                switch (lifecycleEvent.getType()) {
                    case OPENED:
                        Log.d(TAG, "Stomp connection opened: " + lifecycleEvent.getMessage());
                        break;

                    case ERROR:
                        Log.e(TAG, "Error", lifecycleEvent.getException());
                        break;

                    case CLOSED:
                        Log.d(TAG, "Stomp connection closed: " + lifecycleEvent.getHandshakeResponseHeaders());
                        break;
                }
            }
        });

        mStompClient.connect();

        mStompClient.topic("/topic/chat/" + roomID).subscribe(new Action1<StompMessage>() {
            @Override
            public void call(StompMessage topicMessage) {
                Log.d(TAG, topicMessage.getPayload());
                updateChatOutput(topicMessage.getPayload());
            }
        });

        mStompClient.send("/topic/hello-msg-mapping", "My first STOMP message!").subscribe();



        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Log.v(TAG, "Sending " + chatText.getText().toString());
                    sendMessage(chatText.getText().toString());
                } catch(Exception e) {
                    // TODO: graceful message and trying to reconnect
                    Log.d(TAG, "No Socket :( ");
                }

                chatText.post(new Runnable() {
                    public void run() {
                        chatText.setText("");
                    }
                });
            }
        });
    }

    private void updateChatOutput(final String text) {
        chatOutput.post(new Runnable() {
            public void run() {
                chatOutput.append(text + "\n");
            }
        });
    }

    public void sendMessage(String message) {
        mStompClient.send("/app/chat/1", message)
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object aVoid) {
                        Log.d(TAG, "STOMP echo send successfully");
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "Error send STOMP echo", throwable);
                    }
                });
    }

}

@@ -281,16 +281,301 @@
 tView;%0A%0A
+import com.google.android.gms.common.api.Result;%0Aimport com.google.android.gms.tasks.Task;%0Aimport com.google.firebase.auth.FirebaseAuth;%0Aimport com.google.firebase.auth.FirebaseAuthProvider;%0Aimport com.google.firebase.auth.FirebaseUser;%0Aimport com.google.firebase.auth.GetTokenResult;%0A
 import c
@@ -766,16 +766,58 @@
 .Stomp;%0A
+import ua.naiksoftware.stomp.StompHeader;%0A
 import u
@@ -934,16 +934,68 @@
 ashMap;%0A
+import java.util.LinkedList;%0Aimport java.util.List;%0A
 import j
@@ -1787,30 +1787,75 @@
 tToken()
-.toString());%0A
+);%0A        mStompHeaders.put(%22greetings%22, %22Hoi Mile!%22);%0A%0A//
         
@@ -2000,16 +2000,26 @@
 0/socket
+/websocket
 %22, mStom
@@ -2754,32 +2754,408 @@
  %7D%0A        %7D);%0A%0A
+        String token = FirebaseAuth.getInstance()%0A                .getCurrentUser()%0A                .getToken(false)%0A                .getResult()%0A                .getToken(); // (%E0%B2%A0_%E0%B2%A0)%0A%0A        Log.d(TAG, %22our token: %22 + token);%0A%0A        StompHeader header = new StompHeader(%22token%22, token );%0A        List%3CStompHeader%3E headers = new LinkedList();%0A        headers.add(header);%0A%0A
         mStompCl
@@ -3167,16 +3167,23 @@
 connect(
+headers
 );%0A%0A    

add authentication from chat to server