/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ntels.onecable.admin.common.ble;


import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.util.Dlog;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;

import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;

/**
 * Service for managing connection and data communication with a GATT server hosted on a
 * given Bluetooth LE device.
 */
public class BluetoothLeService extends Service {
    public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_STATUS_133 = "com.example.bluetooth.le.ACTION_GATT_133";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA";
    public final static UUID UUID_APPLY_CHR_UUID = UUID.fromString(GattAttributeResolver.APPLY_CHR_UUID);
    private final static String TAG = BluetoothLeService.class.getSimpleName();
    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;
    private final IBinder mBinder = new LocalBinder();
    String reConnectAddress = "";
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private BluetoothGattServer mBluetoothGattServer;
    private int mConnectionState = STATE_DISCONNECTED;
    // Implements callback methods for GATT events that the app cares about.  For example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            Dlog.i(TAG, "status =" + status);
            Dlog.i(TAG, "newState =" + newState);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    intentAction = ACTION_GATT_CONNECTED;
                    mConnectionState = STATE_CONNECTED;
                    broadcastUpdate(intentAction);
                    Dlog.i(TAG, "Connected to GATT server.");
                    // Attempts to discover services after successful connection.
//                Dlog.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    intentAction = ACTION_GATT_DISCONNECTED;
                    mConnectionState = STATE_DISCONNECTED;
                    disconnect();
                    close();
                    Dlog.i(TAG, "Disconnected from GATT server.");
                    broadcastUpdate(intentAction);
                }
            }else {
//                Dlog.d(TAG, "onConnectionStateChange received: " + status);
//                intentAction = ACTION_GATT_STATUS_133;
//                mConnectionState = STATE_DISCONNECTED;
//                disconnect();
//                close();
//                broadcastUpdate(intentAction);
//                connect(reConnectAddress);
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                disconnect();
                close();
                Dlog.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Dlog.d(TAG, "onServicesDiscovered Read: " + status);
//            Dlog.d(TAG, "onServicesDiscovered Changed: "+  gatt.getService(MY_UUID).getCharacteristic(charUUID));
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Dlog.w(TAG, "onServicesDiscovered received: " + status);
            }
        }


        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Dlog.d(TAG, "Characteristic Read: " + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Dlog.d(TAG, "Characteristic Changed: " + characteristic.getValue());
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    };
//    private static final UUID MY_UUID = UUID.fromString("00001801-0000-1000-8000-00805f9b34fb");
//    private static final UUID charUUID = UUID.fromString("00002a01-0000-1000-8000-00805f9b34fb");

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);

        byte[] bytesData = characteristic.getValue();
        String s = byte2HexStr(bytesData);
        String data = "";
        if (s.equals("00")) {
            data = "0";
        } else if (s.equals("01")) {
            data = "1";
        } else if (s.equals("02")) {
            data = "2";
        } else {
            data = print10(s);
        }
        Dlog.v("jino", "S = " + s);
        if (data != null) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put(Constants.KEY_UUID, characteristic.getUuid());
                jsonObject.put(Constants.KEY_DATA, data);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            intent.putExtra(EXTRA_DATA, jsonObject.toString());
        }
        sendBroadcast(intent);
    }

    /**
     * 将16进制 转换成10进制
     */
    public static String print10(String str) {

        StringBuffer buff = new StringBuffer();
        String array[] = str.split(" ");
        for (int i = 0; i < array.length; i++) {
            int num = Integer.parseInt(array[i], 16);
            buff.append(String.valueOf((char) num));
        }
        return buff.toString();
    }

    /**
     * byte转16进制
     */
    public static String byte2HexStr(byte[] b) {

        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }
    public void setReConnectAddress(String address) {
        reConnectAddress = address;
    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
        close();
        return super.onUnbind(intent);
    }

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Dlog.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Dlog.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        //JDD - lets go ahead and start our GATT server now
//        addDefinedGattServerServices();
//        addGattServerService();
        return true;
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     *
     * @return Return true if the connection is initiated successfully. The connection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public boolean connect1(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Dlog.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Dlog.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

        if (device == null) {
            Dlog.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
//        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
//        mBluetoothGatt = (new BleConnectionCompat(BluetoothLeService.this)).connectGatt(device, false, mGattCallback);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Little hack with reflect to use the connect gatt with defined transport in Lollipop
            Method connectGattMethod = null;

            try {
                connectGattMethod = device.getClass().getMethod("connectGatt", Context.class, boolean.class, BluetoothGattCallback.class, int.class);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

            try {
                mBluetoothGatt = (BluetoothGatt) connectGattMethod.invoke(device, this, false, mGattCallback, TRANSPORT_LE);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else  {
            mBluetoothGatt = (new BleConnectionCompat(BluetoothLeService.this)).connectGatt(device, false, mGattCallback);
        }
        Dlog.d(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        setReConnectAddress(address);
        mConnectionState = STATE_CONNECTING;
        return true;
    }

    public void connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Dlog.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Dlog.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return;
            } else {
                return;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {


                if (device == null) {
                    Dlog.w(TAG, "Device not found.  Unable to connect.");
                    return;
                }
                // We want to directly connect to the device, so we are setting the autoConnect
                // parameter to false.
//        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    // Little hack with reflect to use the connect gatt with defined transport in Lollipop
                    Method connectGattMethod = null;

                    try {
                        connectGattMethod = device.getClass().getMethod("connectGatt", Context.class, boolean.class, BluetoothGattCallback.class, int.class);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }

                    try {
                        mBluetoothGatt = (BluetoothGatt) connectGattMethod.invoke(device, this, false, mGattCallback, TRANSPORT_LE);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } else  {
                    mBluetoothGatt = (new BleConnectionCompat(BluetoothLeService.this)).connectGatt(device, false, mGattCallback);
                }

//                mBluetoothGatt = (new BleConnectionCompat(BluetoothLeService.this)).connectGatt(device, false, mGattCallback);
                Dlog.d(TAG, "Trying to create a new connection.");
                mBluetoothDeviceAddress = address;
                setReConnectAddress(address);
                mConnectionState = STATE_CONNECTING;
            }
        });
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The disconnection result
     * is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Dlog.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
     * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt,
     * android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Dlog.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    public void writeRemoteCharacteristic(BluetoothGattCharacteristic characteristic) {

        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Dlog.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.writeCharacteristic(characteristic);
    }

    public Boolean discoverServices(){
       return mBluetoothGatt.discoverServices();

    }


    public boolean writeToCharacteristic(UUID serviceUUID, UUID characteristicUUID, byte[] values) {
        BluetoothGattService gattService = mBluetoothGatt == null ? null : mBluetoothGatt.getService(serviceUUID);
        if (gattService != null) {
            BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(characteristicUUID);
            if (gattCharacteristic != null) {
                gattCharacteristic.setValue(values);
                writeRemoteCharacteristic(gattCharacteristic);
                Dlog.v("jino", "111116");
                return true;
            }
        }
        return false;
    }

    public boolean readToCharacteristic(UUID serviceUUID, UUID characteristicUUID) {
        Dlog.v("jino", "read111111");
        BluetoothGattService gattService = mBluetoothGatt == null ? null : mBluetoothGatt.getService(serviceUUID);
        Dlog.v("jino", "read111112");
        if (gattService != null) {
            Dlog.v("jino", "read111113");
            BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(characteristicUUID);
            Dlog.v("jino", "read111114");
            if (gattCharacteristic != null) {
                Dlog.v("jino", "read111115");
                readCharacteristic(gattCharacteristic);
                Dlog.v("jino", "read111116");
                return true;
            }
        }
        return false;
    }

    public BluetoothGattCharacteristic getCharacteristic(UUID serviceUUID, UUID characteristicUUID) {
        Dlog.v("jino", "read111111");
        BluetoothGattService gattService = mBluetoothGatt == null ? null : mBluetoothGatt.getService(serviceUUID);
        Dlog.v("jino", "read111112");
        if (gattService != null) {
            Dlog.v("jino", "read111113");
            BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(characteristicUUID);
            Dlog.v("jino", "read111114");
            if (gattCharacteristic != null) {
                Dlog.v("jino", "read111115");
                return gattCharacteristic;
            }
        }
        return null;
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification.  False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Dlog.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
//        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        boolean success = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        if(!success) {
            Dlog.e("------", "Seting proper notification status for characteristic failed!");
        }

        // This is also sometimes required (e.g. for heart rate monitors) to enable notifications/indications
        // see: https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(GattAttributeResolver.CLIENT_CHARACTERISTIC_CONFIG));
        if(descriptor != null) {
            Dlog.v(TAG, "jino BluetoothAdapter descriptor");
            byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
            descriptor.setValue(val);
            mBluetoothGatt.writeDescriptor(descriptor);
        }
    }

    /**
     * Retrieves a list of supported GATT services on the connected device. This should be
     * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) return null;

        return mBluetoothGatt.getServices();
    }

    public void addGattServerService(BluetoothGattService service) {
        mBluetoothGattServer.addService(service);
    }

//    public void addDefinedGattServerServices() {
//        mBluetoothGattServer = mBluetoothManager.openGattServer(this, mGattServerCallback);
//        BluetoothGattService service = new BluetoothGattService(UUID.fromString(SampleGattAttributes.FAN_CONTROL_SERVICE_UUID),
//                BluetoothGattService.SERVICE_TYPE_PRIMARY);
//        BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString(SampleGattAttributes
//                .FAN_OPERATING_STATE), BluetoothGattCharacteristic.FORMAT_UINT8, BluetoothGattCharacteristic.PERMISSION_WRITE);
//
//        service.addCharacteristic(characteristic);
//        mBluetoothGattServer.addService(service);
//
//        Dlog.d("HELLO", "Created our own GATT server.\r\n");
//
//    }
//    public void addDefinedGattServerServices() {
//        mBluetoothGattServer = mBluetoothManager.openGattServer(this, mGattServerCallback);
//        BluetoothGattService service = new BluetoothGattService(UUID.fromString(GattAttributeResolver.WFNPS_UUID),
//                BluetoothGattService.SERVICE_TYPE_PRIMARY);
//        BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString(GattAttributeResolver
//                .FAN_OPERATING_STATE), BluetoothGattCharacteristic.FORMAT_UINT8, BluetoothGattCharacteristic.PERMISSION_WRITE);
//
//        service.addCharacteristic(characteristic);
//        mBluetoothGattServer.addService(service);
//
//        Dlog.d("HELLO", "Created our own GATT server.\r\n");
//
//    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }
}