package com.example.imlinkclient.helpr;

import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.example.imlinkclient.Constants;
import com.example.imlinkclient.MainClientActivity;
import com.mxnavi.mlink.serversdk.service.IMlinkService;
import com.mxnavi.mlink.serversdk.service.IMlinkServiceClient;

import java.util.Arrays;

/**
 * AIDL连接
 */
public class MLinkServiceHelper {
    private final static String TAG = "MLinkServiceHelper";
    private static volatile MLinkServiceHelper mInstance = null;
    private Context mContext;
    private boolean mServiceBounded;
    private IMlinkService mIMlinkService;
    private MainClientActivity.MainHandler mMainHandler;

    private MLinkServiceHelper() {
    }

    public static MLinkServiceHelper getInstance() {
        // 二次校验，防止多线程调用导致出现多个实例
        if (mInstance == null) {
            synchronized (MLinkServiceHelper.class) {
                if (mInstance == null) {
                    mInstance = new MLinkServiceHelper();
                }
            }
        }
        return mInstance;
    }

    public void init(Application application) {
        mContext = application.getApplicationContext();
    }

    public void setHandler(MainClientActivity.MainHandler handler) {
        mMainHandler = handler;
    }

    public Context getApplicationContext() {
        return mContext;
    }

    public boolean bindMLinkService() {
        if (mServiceBounded) {
            return true;
        }
        Intent intent = new Intent();
//        Action：com.mxnavi.mlink.ACTION_BIND_MLINK_SERVICE
//        Package：com.mxnavi.applauncher
        intent.setAction("com.mxnavi.mlink.ACTION_BIND_MLINK_SERVICE");
        intent.setPackage("com.mxnavi.applauncher");
        mServiceBounded = mContext.bindService(intent, mConnection, Service.BIND_AUTO_CREATE);
        return mServiceBounded;
    }

    ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIMlinkService = IMlinkService.Stub.asInterface(service);
            try {
                if (mIMlinkService != null){
                    mIMlinkService.registerMlinkServiceClient(mMlinkClient);
                }
            } catch (RemoteException  | SecurityException e) {
                e.printStackTrace();
            }

            mMainHandler.obtainMessage(MainClientActivity.MainHandler.MSG_AIDL_STATUS, 1, -1)
                    .sendToTarget();
            Log.d(TAG, "onServiceConnected aidl连接成功");

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            try {
                mIMlinkService.unregisterMlinkServiceClient(mMlinkClient);
            } catch (RemoteException  | SecurityException e) { 
                e.printStackTrace();
            }
            mMainHandler.obtainMessage(MainClientActivity.MainHandler.MSG_AIDL_STATUS, 0, -1)
                    .sendToTarget();
            Log.d(TAG, "onServiceConnected aidl连接断开");
        }
    };

    IMlinkServiceClient.Stub mMlinkClient = new IMlinkServiceClient.Stub() {

        @Override
        public void onConnectionStateChanged(boolean isConnected) throws RemoteException {
            Log.d(TAG, "onConnectionStateChanged :" + isConnected);

        }

        @Override
        public void onHUCommand(final int cmd, final Bundle bundle) throws RemoteException {
            Log.d(TAG, "接收到aidl数据 onHUCommand : " + cmd + "  bundle : " + bundle.toString());
            switch (cmd) {
                case Constants.CMD_BLUETOOTH_DATA:
                    // 发送蓝牙数据
                    sendMessage(MainClientActivity.MainHandler.MSG_BT_DATA_T, bundle);
//                    Log.d(TAG, "接收到aidl蓝牙数据 onHUCommand : " + cmd + "  bundle : " + Arrays.toString(btData));
//                    byte[] btData = bundle.getByteArray(Constants.KEY_BT_BYTES);
//                    Log.d(TAG, "onHUCommand btData.length : " +btData.length);
//                    mMainHandler.obtainMessage(MainClientActivity.MainHandler.MSG_BT_DATA_T, -1, -1, btData).sendToTarget();
                    break;
                case Constants.CMD_WIFI_CONFIG_INFO:
                    // 配置 wifi
                    sendMessage(MainClientActivity.MainHandler.MSG_WIFI_CONFIG, bundle);
                    break;
            }
        }
    };

    private void sendMessage(int what, Bundle data) {
        Message message = mMainHandler.obtainMessage(what);
        message.setData(data);
        message.sendToTarget();
    }

    /**
     * mIMlinkService 接口包装 start
     **/
    public boolean onBtConnectionStatus(boolean isConnected, String mac) {
        if (mIMlinkService != null) {
            try {
                Log.d(TAG, "onBtConnectionStatus 蓝牙连接状态： "+isConnected +"  mac :" + mac);

                return mIMlinkService.onBtConnectionStatus(isConnected, mac);
            } catch (RemoteException  | SecurityException e) { 
                e.printStackTrace();
            }
        }
        return false;
    }

    public boolean onReceivedBtData(byte[] data) {
        if (mIMlinkService != null) {
            try {
                Log.d(TAG, "onReceivedBtData 发送数据： " + Arrays.toString(data));
                return mIMlinkService.onReceivedBtData(data);
            } catch (RemoteException  | SecurityException e) { 
                e.printStackTrace();
            }
        }
        return false;
    }



    public boolean onWifiConnectionStatus(boolean isConnected, String mac) {
        if (mIMlinkService != null) {
            try {
                return mIMlinkService.onWifiConnectionStatus(isConnected, mac);
            } catch (RemoteException  | SecurityException e) { 
                e.printStackTrace();
            }
        }
        return false;
    }

    public IMlinkService getmIMlinkService() {
        return mIMlinkService;
    }
    /** mIMlinkService 接口包装 end **/
}
