package service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import engine.addressDao;
import project.zfy.com.mymobilesalf.R;
import utils.ConstantValue;
import utils.SpUtil;

/**
 * Created by lenovo on 2016/6/14.
 */
public class addressService extends Service {


    private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();

    private TelephonyManager mTelephonyManager;
    private myPhoneStateListener mMyPhoneStateListener;
    private View mViewToast;
    private WindowManager mWindowManager;
    private String mAddress;
    private TextView tv_toast;
    private int[] mDrawableId;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tv_toast.setText(mAddress);


        }
    };
    private innerOutCallReceiver mInnerOutCallReceiver;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override//在服务创建的时候调用
    /*
    * 1.管理Toast
    * 2.监听电话的状态，在响铃状态时，开启，挂断电话时，移除 (服务开启的时候监听，关闭的时候电话状态就不监听，
    * 单纯的关闭服务是不能阻止监听状态的)
    * */
    public void onCreate() {

        super.onCreate();
        //1.拿到电话管理者对象
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //2.监听电话状态
        mMyPhoneStateListener = new myPhoneStateListener();
        mTelephonyManager.listen(mMyPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        //获取窗体对象
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);


        //播出电话的广播过滤条件 （权限！！！）
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
        //创建广播接收者
        mInnerOutCallReceiver = new innerOutCallReceiver();
        registerReceiver(mInnerOutCallReceiver,intentFilter);
    }

    private class innerOutCallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播后，显示自定义吐司，显示拨出号码的归属地
                //拿到拨出号码的字符串
            String phone = getResultData();
            showToast(phone);
            
        }
    }


    private class myPhoneStateListener extends PhoneStateListener {
        @Override//当电话状态改变时，触发的方法
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                //CALL_STATE_IDLE 空闲状态，没有电话打进来，或者接电话之后的挂断  （移除Toast）
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.d("------>", "空闲状态");
                    //电话挂断了，将自定义的吐司移除
                    dismissToast();

                    break;
                //响铃状态，有电话打进来但是还没有接听或者挂断   （展示Toast）
                case TelephonyManager.CALL_STATE_RINGING:
                    //电话来了，展示自定义吐司
                    showToast(incomingNumber);
                    Log.d("------>", "响铃状态");

                    break;
                //摘机状态，也就是正在通话中的状态
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    /*showToast(incomingNumber);*/

                    break;

                default:
                    break;
            }


            super.onCallStateChanged(state, incomingNumber);
        }


    }

    private void dismissToast() {
        if (mWindowManager != null && mViewToast != null) {
            mWindowManager.removeView(mViewToast);
        }
    }


    /**
     * 根据源码，自定义吐司显示
     *
     * @param incomingNumber 拨入的电话
     *                       created at 2016/6/15 14:22
     * @return void
     * @author zfy
     */

    private void showToast(String incomingNumber) {
       /* Toast.makeText(getApplicationContext(),incomingNumber,Toast.LENGTH_SHORT).show();*/

        final WindowManager.LayoutParams params = mParams;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.format = PixelFormat.TRANSLUCENT;
        //在响铃的时候显示吐司,和电话类型一致
        params.type = WindowManager.LayoutParams.TYPE_PHONE;
        params.setTitle("Toast");
        params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE //默认是可以拿到焦点的
                /*| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE  默认是可以被触摸的*/;

        //指定指定吐司所在的位置
        params.gravity = Gravity.LEFT + Gravity.TOP;

        //制定吐司的布局文件 xml-->view ，然后将吐司挂载到windowManager窗体上
        mViewToast = View.inflate(this, R.layout.toast_view, null);

        mViewToast.setOnTouchListener(new View.OnTouchListener() {
            private int startX;
            private int startY;

            //对不同的事件做不同的逻辑处理
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int moveX = (int) event.getRawX();
                        int moveY = (int) event.getRawY();

                        int disX = moveX - startX;
                        int disY = moveY - startY;

                        params.x = params.x + disX;
                        params.y = params.y + disY;

                        //容错处理
                        if (params.x < 0) {
                            params.x = 0;
                        }
                        if (params.y < 0) {
                            params.y = 0;
                        }
                        if (params.x > mWindowManager.getDefaultDisplay().getWidth() - mViewToast.getWidth()) {
                            params.x = mWindowManager.getDefaultDisplay().getWidth();
                        }
                        if (params.y > mWindowManager.getDefaultDisplay().getHeight() - mViewToast.getHeight() - 22) {
                            params.x = mWindowManager.getDefaultDisplay().getHeight() - 22;
                        }

                        //告知窗体吐司需要按照手势的移动去做位置的更新
                        mWindowManager.updateViewLayout(mViewToast, params);

                        //3,重置一次启示坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();

                        break;

                    case MotionEvent.ACTION_UP:
                        SpUtil.putInt(getApplicationContext(), ConstantValue.LOCATION_X, params.x);
                        SpUtil.putInt(getApplicationContext(), ConstantValue.LOCATION_Y, params.y);

                        break;
                }

                return true;
            }
        });

        //从SP中拿到索引，然后匹配图片
        mDrawableId = new int[]{R.drawable.call_locate_white,
                R.drawable.call_locate_orange,
                R.drawable.call_locate_blue,
                R.drawable.call_locate_gray,
                R.drawable.call_locate_green};
        int drawableIndex = SpUtil.getInt(getApplicationContext(), ConstantValue.TOAST_STYLE, 0);
        tv_toast = (TextView) mViewToast.findViewById(R.id.tv_toast);
        tv_toast.setBackgroundResource(mDrawableId[drawableIndex]);


        //读取SP中存储吐司位置的左上角坐标值
        params.x = SpUtil.getInt(getApplicationContext(), ConstantValue.LOCATION_X, 0);
        params.y = SpUtil.getInt(getApplicationContext(), ConstantValue.LOCATION_Y, 0);

        //在窗体上挂载viw  需要权限
        mWindowManager.addView(mViewToast, params);

        //拿到了电话号码之后，要做电话号码的查询工作
        query(incomingNumber);


    }

    private String query(final String incomingNumber) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mAddress = addressDao.getAddress(incomingNumber);
                mHandler.sendEmptyMessage(0);
            }
        }).start();

        return mAddress;
    }


    @Override//在服务销毁的时候调用
    public void onDestroy() {
        //取消对电话状态的监听
        if (mTelephonyManager != null && mMyPhoneStateListener != null) {

            mTelephonyManager.listen(mMyPhoneStateListener, PhoneStateListener.LISTEN_NONE);

        }
        if (mInnerOutCallReceiver!=null){
            //注销去点广播接收者
            unregisterReceiver(mInnerOutCallReceiver);
        }


        super.onDestroy();
    }




}
