package com.nbusy.app;

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.common.eventbus.Subscribe;

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

/**
 * A fragment representing a single Chat detail screen, along with the messages in the chat.
 * This fragment is either contained in a {@link ChatListActivity}
 * in two-pane mode (on tablets) or a {@link ChatDetailActivity} on handsets.
 */
public class ChatDetailFragment extends ListFragment implements View.OnClickListener {

    public static final String ARG_ITEM_ID = "item_id"; // fragment argument representing the item ID that this fragment represents
    private final Worker worker = WorkerSingleton.getWorker();
    private String chatId;
    private List<Message> messages; // chat messages that this fragment is presenting
    private Map<String, Integer> messageIDtoIndex; // message ID -> messages[index]
    private MessageListArrayAdapter messageAdapter;
    private ListView messageListView;
    private EditText messageBox;
    private Button sendButton;

    private void sendMessage() {
        // do not submit blank lines
        String message = messageBox.getText().toString().trim();
        if (message.isEmpty()) {
            return;
        }

        // add message to the UI, and clear message box
        Message msg = new Message(Integer.toString(messages.size()), "me", message, "now", false);
        messageAdapter.add(msg);
        messageIDtoIndex.put(msg.id, messages.size() - 1);
        messageBox.setText("");

        // send the message to the server
        worker.sendMessage(msg);
    }

    private void addCheckMarkToMessage(String msgID, boolean doubleCheck) {
        // update the check mark on the updated item only as per
        // http://stackoverflow.com/questions/3724874/how-can-i-update-a-single-row-in-a-listview
        int location = messageIDtoIndex.get(msgID);
        if (location == 0) {
            return;
        }

        View v = messageListView.getChildAt(location - messageListView.getFirstVisiblePosition());
        if (v != null) {
            v.findViewById(R.id.check).setVisibility(View.VISIBLE);
            Message msg = messages.get(location);
            msg.sentToServer = true;
            msg.delivered = doubleCheck;
            return;
        }

        // element is not visible on the view yet so we have to update the entire list view via adapter now
        Message msg = messageAdapter.getItem(location);
        msg.sentToServer = true;
        msg.delivered = doubleCheck;
    }

    /**************************
     * ListFragment Overrides *
     **************************/

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle arguments = getArguments();
        if (arguments.containsKey(ARG_ITEM_ID)) {
            chatId = (String) arguments.get(ARG_ITEM_ID);

            // load the content specified by the fragment arguments
            messages = new ArrayList<>();
            messageIDtoIndex = new HashMap<>();

            Message m1 = new Message("1", "Teoman Soygul", "Lorem ip sum my message...", "8:50", true);
            m1.sentToServer = m1.delivered = true;
            Message m2 = new Message("2", "User ID: " + chatId, "Test test.", "Just now", false);
            m2.sentToServer = m2.delivered = true;
            messages.add(m1);
            messageIDtoIndex.put(m1.id, messages.size() - 1);
            messages.add(m2);
            messageIDtoIndex.put(m2.id, messages.size() - 1);

            messageAdapter = new MessageListArrayAdapter(getActivity(), messages);
            setListAdapter(messageAdapter);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_chat_detail, container, false);

        messageListView = (ListView) rootView.findViewById(android.R.id.list);
        sendButton = (Button) rootView.findViewById(R.id.send_button);
        sendButton.setOnClickListener(this);
        messageBox = (EditText) rootView.findViewById(R.id.edit_message);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        worker.getEventBus().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        worker.getEventBus().unregister(this);
    }

    /**********************************
     * View.OnClickListener Overrides *
     **********************************/

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_button:
                sendMessage();
                break;
        }
    }

    /******************************
     * Worker Event Subscriptions *
     ******************************/

    @Subscribe
    public void addCheckMarkToMessage(Worker.MessageSentEvent e) {
        addCheckMarkToMessage(e.id, false);
    }

    @Subscribe
    public void addDoubleCheckMarkToMessage(Worker.MessageDeliveredEvent e) {
        addCheckMarkToMessage(e.id, true);
    }
}

@@ -76,16 +76,41 @@
 Bundle;%0A
+import android.util.Log;%0A
 import a
@@ -433,16 +433,39 @@
 til.Map;
+%0Aimport java.util.UUID;
 %0A%0A/**%0A *
@@ -792,16 +792,96 @@
 ener %7B%0A%0A
+    private static final String TAG = ChatDetailFragment.class.getSimpleName();%0A
     publ
@@ -1712,40 +1712,35 @@
 age(
-Integer.toString(messages.size()
+UUID.randomUUID().toString(
 ), %22
@@ -1772,41 +1772,8 @@
 e);%0A
-        messageAdapter.add(msg);%0A
     
@@ -1812,36 +1812,65 @@
  messages.size()
- - 1
+);%0A        messageAdapter.add(msg
 );%0A        messa
@@ -2442,24 +2442,132 @@
  != null) %7B%0A
+            Log.d(TAG, %22Message ID: %22 + location + %22, is visible and check mark status is being updated.%22);%0A
             
@@ -3585,11 +3585,36 @@
 age(
-%221%22
+UUID.randomUUID().toString()
 , %22T
@@ -3765,11 +3765,36 @@
 age(
-%222%22
+UUID.randomUUID().toString()
 , %22U
@@ -3902,38 +3902,8 @@
 ue;%0A
-            messages.add(m1);%0A
     
@@ -3953,20 +3953,16 @@
 s.size()
- - 1
 );%0A     
@@ -3982,17 +3982,17 @@
 es.add(m
-2
+1
 );%0A     
@@ -4045,12 +4045,38 @@
 ze()
- - 1
+);%0A            messages.add(m2
 );%0A%0A

simplify message id logic