package com.github.sharkspeed.ngtodo;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.github.sharkspeed.ngtodo.db.TaskContract;
import com.github.sharkspeed.ngtodo.db.TaskDbHelper;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TaskDbHelper mHelper;
    private ListView mTaskListView;
    private ArrayAdapter<String> mAdapter;  // 帮助将数据添加到 ListView 中

    private static final String SERVERIP = "192.168.2.221";
    private static final int SERVERPORT = 11000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // points to a file called activity_main.xml in the /res/layout directory of the project
        setContentView(R.layout.activity_main);

        // 初始化其他变量
        // initialize mHelper in the onCreate() method
        mHelper = new TaskDbHelper(this);

        mTaskListView = (ListView)findViewById(R.id.list_todo);

        updateUI();
    }

    DatagramSocket socket = null;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_task: // 对应 main_menu.xml 中的 id
//                new Thread(new Client()).start();
                Log.d(TAG, "Add a new task");

                final EditText taskEditText = new EditText(this);
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("Add a new task")
                        .setMessage("What do you want to do next?")
                        .setView(taskEditText)
                        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String task = String.valueOf(taskEditText.getText());
                                Log.d(TAG, "Task to add: " + task);
                                SQLiteDatabase db = mHelper.getWritableDatabase();  // priavte TaskDbHelper
                                ContentValues values = new ContentValues();
                                values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                                db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
                                        null,
                                        values,
                                        SQLiteDatabase.CONFLICT_REPLACE);
                                db.close();
                                updateUI();
                            }
                        })
                        .setNegativeButton("Cancel", null)
                        .create();
                dialog.show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void deleteTask(View view) {
        View parent = (View) view.getParent();
        TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
        String task = String.valueOf(taskTextView.getText());
        SQLiteDatabase db = mHelper.getWritableDatabase();
        // 根据 todoItem title 内容删除对应数据
        db.delete(
                TaskContract.TaskEntry.TABLE,
                TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",
                new String[]{task}
        );
        db.close();
        updateUI();
    }

    private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();

        // read from db
        SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor = db.query(
                TaskContract.TaskEntry.TABLE,
                new String[]{
                        TaskContract.TaskEntry._ID,
                        TaskContract.TaskEntry.COL_TASK_TITLE,
                },
                null, null, null, null, null
        );
        while(cursor.moveToNext()) {
            int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
            Log.d(TAG, "Task: " + cursor.getString(idx));
            taskList.add(cursor.getString(idx));  // 添加到 ArrayList 中
        }

        if (mAdapter == null) {
            mAdapter = new ArrayAdapter<>(
                    this,
                    R.layout.item_todo,
                    R.id.task_title,
                    taskList
            );
            mTaskListView.setAdapter(mAdapter);  // 设置为 ListView 的 adapter
        } else {
            // 如果已经有数据显示，就清空它再填充
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }

        cursor.close();
        db.close();
    }

    public class Client implements Runnable {
        public void run() {
            // 向局域网UDP广播信息：Hello, World!
            try {
                InetAddress serverAddress = InetAddress.getByName(SERVERIP);
                System.out.println("Client: Start connecting\n");
                socket = new DatagramSocket(SERVERPORT);
                byte[] buf = "Hello, World!".getBytes();
                DatagramPacket packet = new DatagramPacket(buf, buf.length,
                        serverAddress, SERVERPORT);
                System.out.println("Client: Sending ‘" + new String(buf)
                        + "’\n");
                socket.send(packet);
                System.out.println("Client: Message sent\n");
                System.out.println("Client: Succeed!\n");
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 接收UDP广播，有的手机不支持
            while (true) {
                byte[] recbuf = new byte[255];
                DatagramPacket recpacket = new DatagramPacket(recbuf,
                        recbuf.length);
                try {
                    socket.receive(recpacket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("Server: Message received: ‘"
                        + new String(recpacket.getData()) + "’\n");
                System.out.println("Server: IP " + recpacket.getAddress()
                        + "’\n");
            }
        }
    }
}
