package com.example.roman.vk_android_coursework;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.vk.sdk.api.VKApi;
import com.vk.sdk.api.VKApiConst;
import com.vk.sdk.api.VKParameters;
import com.vk.sdk.api.VKRequest;
import com.vk.sdk.api.VKResponse;
import com.vk.sdk.api.methods.VKApiMessages;
import com.vk.sdk.api.model.VKApiMessage;
import com.vk.sdk.api.model.VKList;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by roman on 01.05.16.
 */
public class DialogActivity extends AppCompatActivity {

    private ListView messageList;
    private Button sendButton;
    private EditText messageText;
    private List<String> messagesBody = new Vector<String>();
    ArrayAdapter<String> arrayAdapter;
    private int lastMessageId;
    MyService myService = new MyService();

    /**
     * Некое подобие сервиса, работает в фоне.
     * Каждые 3 секунды получает сообщения с сервера.
     */
    class MyService implements Runnable {

        private boolean isRunning = true;

        public void powerOff() {
            isRunning = false;
        }

        @Override
        public synchronized void run() {

            Bundle b = getIntent().getExtras();
            final String user_id = b.getString("user_id");
            final String user_first_name = b.getString("user_first_name");

            while (isRunning) {
                try {
                    wait(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                VKRequest request = new VKRequest("messages.getHistory", VKParameters.from(VKApiConst.USER_ID, user_id, VKApiConst.COUNT, 10, VKApiConst.OFFSET, -10, VKApiConst.START_MESSAGE_ID, lastMessageId));
                request.executeWithListener(new VKRequest.VKRequestListener() {
                    @Override
                    public void onComplete(VKResponse response) {
                        super.onComplete(response);

                        VKList<VKApiMessage> messages = new VKList<VKApiMessage>();

                        try {
                            JSONArray array = response.json.getJSONObject("response").getJSONArray("items");

                            addJSONArrayObjectsToMessagesArray(array, messages);

                            for (VKApiMessage message : messages) {

                                if(message.id <= lastMessageId) {
                                    break;
                                }

                                if (message.out) {
                                    messagesBody.add(0, "You:\n" + message.body);
                                } else {
                                    messagesBody.add(0, user_first_name + ":\n" + message.body);
                                }
                                messagesBody.remove(messagesBody.size() - 1);
                                arrayAdapter.notifyDataSetChanged();
                                lastMessageId = message.id;
                            }
                            messages.clear();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        }
    }

    /**
     * Отчистка слоя после нажатия "Back"
     */
    @Override
    public void onBackPressed() {
        myService.powerOff();
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);

        Bundle b = getIntent().getExtras();
        final String user_id = b.getString("user_id");
        final String user_first_name = b.getString("user_first_name");

        messageList = (ListView) findViewById(R.id.messageList);
        sendButton = (Button) findViewById(R.id.sendButton);
        messageText = (EditText) findViewById(R.id.messageText);

        sendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(messageText.length() != 0) {

                    VKRequest rec = new VKRequest("messages.send", VKParameters.from(VKApiConst.USER_ID, user_id, VKApiConst.MESSAGE, messageText.getText().toString()));

                    rec.executeWithListener(new VKRequest.VKRequestListener() {
                        @Override
                        public void onComplete(VKResponse response) {
                            super.onComplete(response);
                            messageText.getText().clear();
                            System.out.println("message send");
                        }
                    });
                }
            }
        });

        /**
         * Получение первых сообщений до старта сервиса, чтоб ему было от чего отталкиваться
         */
        VKRequest request = new VKRequest("messages.getHistory", VKParameters.from(VKApiConst.USER_ID, user_id, VKApiConst.COUNT, 30, VKApiConst.REV, 0));
        request.executeWithListener(new VKRequest.VKRequestListener() {
            @Override
            public void onComplete(VKResponse response) {
                super.onComplete(response);

                VKList<VKApiMessage> messages = new VKList<VKApiMessage>();

                try {
                    JSONArray array = response.json.getJSONObject("response").getJSONArray("items");

                    addJSONArrayObjectsToMessagesArray(array, messages);

                    lastMessageId = messages.get(0).id;

                    for (VKApiMessage message : messages) {
                        if (message.out) {
                            messagesBody.add("You:\n" + message.body);
                        } else {
                            messagesBody.add(user_first_name + ":\n" + message.body);
                        }
                    }
                    messages.clear();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                arrayAdapter = new ArrayAdapter<String>(DialogActivity.this,
                        R.layout.message, messagesBody);

                messageList.setAdapter(arrayAdapter);

                ExecutorService exec = Executors.newFixedThreadPool(1);
                exec.execute(myService);
                exec.shutdown();
            }


         });
    }

    /**
     * Копируем JSON в массив сообщений
     * @param a - копируемый массив JSON
     * @param b - список сообщений
     * @throws JSONException
     */
    private void addJSONArrayObjectsToMessagesArray(JSONArray a, VKList<VKApiMessage> b) throws JSONException {
        for (int i = 0; i < a.length(); ++i) {
            b.add(new VKApiMessage(a.getJSONObject(i)));
        }
        a = null;
    }
}
