/**
 * Copyright 2018 thedamfr
 * 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.
 * Copyright (c) 2018 NXP
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.thedamfr.android.BleEventAdapter.service.gatt;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import com.thedamfr.android.BleEventAdapter.BleEventAdapter;
import com.thedamfr.android.BleEventAdapter.BleEventBus;
import com.thedamfr.android.BleEventAdapter.events.CharacteristicChangedEvent;
import com.thedamfr.android.BleEventAdapter.events.CharacteristicReadEvent;
import com.thedamfr.android.BleEventAdapter.events.CharacteristicWriteEvent;
import com.thedamfr.android.BleEventAdapter.events.DescriptorReadEvent;
import com.thedamfr.android.BleEventAdapter.events.DescriptorWriteEvent;
import com.thedamfr.android.BleEventAdapter.events.DiscoveryServiceEvent;
import com.thedamfr.android.BleEventAdapter.events.GattConnectionStateChangedEvent;
import com.thedamfr.android.BleEventAdapter.events.ReadRemoteRssiEvent;
import com.thedamfr.android.BleEventAdapter.events.ReliableWriteCompleted;
import com.thedamfr.android.BleEventAdapter.events.ServiceDiscoveredEvent;

public class GattService extends Service {


    private BleEventBus mBleEventBus;
    private BluetoothGatt mBluetoothGatt;
    private String TAG = this.getClass().getSimpleName();
    private BluetoothDevice mDevice;

    @Override
    public IBinder onBind(Intent intent) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mBleEventBus = BleEventBus.getInstance();
        mDevice = BleEventAdapter.getInstance().getBluetoothDevice();

        if (mBluetoothGatt == null || mBluetoothGatt.connect()) {
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothGatt = mDevice.connectGatt(GattService.this, false, mGattCallBack);
                }
            }, 500);
        }


        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();    //To change body of overridden methods use File | Settings | File Templates.

        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }


    }

    private BluetoothGattCallback mGattCallBack = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            mBleEventBus.post(new GattConnectionStateChangedEvent(mBluetoothGatt, status, newState));

            if (newState == GattConnectionState.STATE_CONNECTED) {
                mBluetoothGatt.discoverServices();
                mBleEventBus.post(new DiscoveryServiceEvent(1));
            } else if (newState == GattConnectionState.STATE_DISCONNECTED) {
//                mBluetoothGatt = mDevice.connectGatt(GattService.this, false, mGattCallBack); // Call if want to auto re-connect.
            }


        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            mBleEventBus.post(new ServiceDiscoveredEvent(mBluetoothGatt, status));
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            mBleEventBus.post(new CharacteristicReadEvent(mBluetoothGatt, characteristic, status));
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            mBleEventBus.post(new CharacteristicWriteEvent(mBluetoothGatt, characteristic, status));
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            mBleEventBus.post(new CharacteristicChangedEvent(mBluetoothGatt, characteristic));
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            mBleEventBus.post(new DescriptorReadEvent(mBluetoothGatt, descriptor, status));
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
            mBleEventBus.post(new DescriptorWriteEvent(mBluetoothGatt, descriptor, status));
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
            mBleEventBus.post(new ReliableWriteCompleted(mBluetoothGatt, status));

        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            mBleEventBus.post(new ReadRemoteRssiEvent(mBluetoothGatt, rssi, status));
        }
    };




}
