package com.streamdata.apps.cryptochat;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

import com.streamdata.apps.cryptochat.models.Contact;
import com.streamdata.apps.cryptochat.models.Message;
import com.streamdata.apps.cryptochat.utils.DateUtils;


public class MessageListActivity extends AppCompatActivity implements View.OnClickListener {

    // TODO: get message list, self contact and target contact from database
    Contact selfContact = new Contact(Contact.selfId, "alex45", "Alex", null);
    Contact targetContact = new Contact(1, "jack_slash", "Jack", null);
    ArrayList<Message> messageList = new ArrayList<>();

    private int lastMessageId;

    private BaseAdapter adapter;
    private ListView listView;
    private EditText messageEditText;

    MessagingService messagingService;
    MessagingHandler messagingHandler;

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

        // TODO: load message history from database
        // TODO: load lastMessageId from settings
        lastMessageId = 0;

        // initializing messaging service and handler
        messagingService = new MessagingService();
        messagingHandler = new MessagingHandler(this);

        // init activity view
        setContentView(R.layout.activity_message_list);

        // setup listView configuration
        float scale = getResources().getDisplayMetrics().density;
        adapter = new MessageListAdapter(this, messageList, scale);
        listView = (ListView) findViewById(R.id.msgListView);
        listView.setAdapter(adapter);

        // setup sendMessageButton configuration
        Button sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
        sendMessageButton.setOnClickListener(this);

        // map message edit text
        messageEditText = (EditText) findViewById(R.id.messageEditText);
    }

    @Override
    protected void onPause() {
        super.onPause();
        messagingService.unbindListener();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // subscribing to incoming messages (all new ones from lastMessageId)
        messagingService.bindListener(messagingHandler, selfContact, targetContact, lastMessageId);
    }

    // handle send message event
    @Override
    public void onClick(View view) {
        String text = messageEditText.getText().toString();

        // ignore empty messages
        if (Objects.equals(text, "")) {
            return;
        }

        // prepare message
        Message message = new Message(
                Message.EMPTY_ID,
                selfContact,
                targetContact,
                text,
                new Date()
        );

        messagingService.sendMessage(messagingHandler, message);

        // update message list
        messageList.add(message);
        adapter.notifyDataSetChanged();

        // clear edit field
        messageEditText.setText("");

        // scroll down
        listView.smoothScrollToPosition(adapter.getCount() - 1);
    }

    private static class MessagingHandler extends Handler {
        // weak bound with UI thread parent activity
        private final WeakReference<MessageListActivity> parentActivityReference;

        public MessagingHandler(MessageListActivity parent) {
            parentActivityReference = new WeakReference<>(parent);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            MessageListActivity parent = parentActivityReference.get();

            if (parent == null) {
                return;
            }

            switch (msg.what) {
                case MessagingService.STATUS_NEW_MESSAGES:
                    // get message list object
                    ArrayList<Message> newMessages = (ArrayList<Message>) msg.obj;

                    // update last received message id
                    parent.lastMessageId = newMessages.get(newMessages.size() - 1).getId();

                    // update message list
                    parent.messageList.addAll(newMessages);
                    parent.adapter.notifyDataSetChanged();

                    // scroll down
                    parent.listView.smoothScrollToPosition(parent.adapter.getCount() - 1);

                    Log.d(MessagingService.MESSAGING_LOG_TAG, "Received messages pack.");
                    break;

                case MessagingService.STATUS_SEND_MESSAGE_SUCCESS:
                    // TODO: handle successfully sent message
                    Log.d(MessagingService.MESSAGING_LOG_TAG, "Message sent successfully.");
                    break;

                case MessagingService.STATUS_SEND_MESSAGE_ERROR:
                    // TODO: handle fail sent message
                    Log.d(MessagingService.MESSAGING_LOG_TAG, "Message sending error.");
                    break;
            }
        }
    }
}

@@ -187,20 +187,96 @@
 id.view.
-View
+KeyEvent;%0D%0Aimport android.view.View;%0D%0Aimport android.view.inputmethod.EditorInfo
 ;%0D%0Aimpor
@@ -402,16 +402,49 @@
 stView;%0D
+%0Aimport android.widget.TextView;%0D
 %0A%0D%0Aimpor
@@ -785,16 +785,25 @@
 Activity
+%0D%0A       
  impleme
@@ -826,16 +826,49 @@
 Listener
+, TextView.OnEditorActionListener
  %7B%0D%0A%0D%0A  
@@ -2460,24 +2460,158 @@
 EditText);%0D%0A
+        messageEditText.setImeActionLabel(%22Send%22, KeyEvent.KEYCODE_ENTER);%0D%0A        messageEditText.setOnEditorActionListener(this);%0D%0A
     %7D%0D%0A%0D%0A   
@@ -3010,83 +3010,462 @@
  // 
-handle send message event%0D%0A    @Override%0D%0A    public void onClick(View view
+send message on button click%0D%0A    @Override%0D%0A    public void onClick(View view) %7B%0D%0A        sendMessage();%0D%0A    %7D%0D%0A%0D%0A    // send message on enter press%0D%0A    @Override%0D%0A    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) %7B%0D%0A        if (actionId == EditorInfo.IME_NULL) %7B%0D%0A            sendMessage();%0D%0A            return true;%0D%0A        %7D%0D%0A        return false;%0D%0A    %7D%0D%0A%0D%0A    // handle send message event%0D%0A    private void sendMessage(
 ) %7B%0D

Send message procedure on enter key press implemented.