package com.example.lenovo.addressbook;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private DatabaseManager dbManager;
    private Cursor contactCursor;
    private ContanctsCursorAdapter contanctsAdapter;

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

        //为列表设置数据适配器
        dbManager = DatabaseManager.getInstance(this);
        contactCursor = dbManager.getContacts();
        contanctsAdapter = new ContanctsCursorAdapter(this, contactCursor, true);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(contanctsAdapter);

        //为列表单项记录设置点击监听器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                intent.putExtra("ID", id);
                startActivityForResult(intent, 0);
            }
        });
    }

    //为主行动器设置关联的工具栏菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //为工具栏实例化菜单
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
        //菜单事件响应
        @Override
        public boolean onOptionsItemSelected (MenuItem item){
            //只要在AndroidManifest.xml文件制定了父行动器，工具栏将自动处理返回按键
            int id = item.getItemId();
            if (id == R.id.add) {
                Intent intent = new Intent(MainActivity.this, AddPerson.class);
                startActivityForResult(intent, 1);
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        //刷新列表
        @Override
        protected void onActivityResult ( int requestCode, int resultCode, Intent data){
            String action = data.getStringExtra("Action");
            if (action == null) {
                return;
            } else {
                //if (action.equalsIgnoreCase("person removed")){
                if (resultCode == RESULT_OK) {
                    Cursor newCursor = dbManager.getContacts();
                    contanctsAdapter.swapCursor(newCursor);
                    contanctsAdapter.notifyDataSetChanged();
                }
            }
        }

    public ListView getListView() {
        return listView;
    }

    //发送短信
    private void sms(String telNumber) {
        Uri sms_uri = Uri.parse("smsto:+" + telNumber);
        Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri);
        startActivity(sms_intent);
    }

    //拨打电话
    private void makeCall(String telNumber) {
        Uri call_uri = Uri.parse("tel:" + telNumber);
        Intent intent = new Intent(Intent.ACTION_CALL, call_uri);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            startActivity(intent);
        }
    }

    //游标适配器
    public class ContanctsCursorAdapter extends CursorAdapter {

        public ContanctsCursorAdapter(Context context, Cursor cursor, boolean autoRequery) {
            super(context, cursor, autoRequery);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return getLayoutInflater().inflate(R.layout.list_item, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView name = (TextView) view.findViewById(R.id.CONTACT_name);
            TextView phone = (TextView) view.findViewById(R.id.CONTACT_phone);

            //设置监听器
            ImageView sms = (ImageView) view.findViewById(R.id.sms);
            ImageView call = (ImageView) view.findViewById(R.id.call);
            sms.setOnClickListener(smsClickListener);
            sms.setContentDescription(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
            call.setOnClickListener(callClickListener);

            call.setContentDescription(cursor.getString(cursor.getColumnIndexOrThrow("phone")));

            //设置每个部件的显示内容
            name.setText(cursor.getString(cursor.getColumnIndexOrThrow("name")));
            phone.setText(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
        }
    }

    /**
     * 使用Toast显示信息
     */
    private void showMessage(String message) {
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    //发送短信按钮监听
    private OnClickListener smsClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final long position = getListView().getSelectedItemId();
            if (position != ListView.INVALID_POSITION) {
                String phoneNumber = (String) v.getContentDescription();
                ;
                sms(phoneNumber);
            }
        }
    };

    //拨打电话按钮监听
    private OnClickListener callClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = getListView().getPositionForView(v);
            if (position != ListView.INVALID_POSITION) {
                String phoneNumber = (String) v.getContentDescription();
                makeCall(phoneNumber);
            }
        }
    };

}
