/**
 * 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.discovery.device;

import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

import com.squareup.otto.Produce;
import com.thedamfr.android.BleEventAdapter.BleEventBus;
import com.thedamfr.android.BleEventAdapter.events.DiscoveredDevicesEvent;
import com.thedamfr.android.BleEventAdapter.events.ScanningEvent;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class DeviceDiscoveryService extends Service {

    private static final long SCAN_PERIOD = 5000;
    private BleEventBus mBleEventBus;
    private Set<BluetoothDevice> mBluetoothDevices = new HashSet<BluetoothDevice>();
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private boolean mScanning = false;

    private ScanCallback mScanCallback;
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothLeScanner mLEScanner;

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

        mBleEventBus = BleEventBus.getInstance();
        mBleEventBus.register(this);

        boolean apiJBorAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;

        boolean isBleAvailable = getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE);
        if (isBleAvailable && apiJBorAbove) {
            final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();
        }else{
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }
            if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
                // Toast.makeText(this, "Pas de Ble, Blaireau", Toast.LENGTH_SHORT).show();
                stopSelf();
            } else {

            initScanCallback();
            scanLeDevice(true);
            }

        return START_NOT_STICKY;
    }

    /**
     * Device scan callback.
     */
    private void initScanCallback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            initCallbackLollipop();
        } else {
            initScanCallbackSupport();
        }
    }
    /**
     * Device scan callback for lollipop and above device.
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void initCallbackLollipop() {
        if (mScanCallback != null) return;
        this.mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                mBluetoothDevices.add(result.getDevice());
                mBleEventBus.post(new DiscoveredDevicesEvent(result.getDevice(), mBluetoothDevices));
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                super.onBatchScanResults(results);
            }

            @Override
            public void onScanFailed(int errorCode) {
                super.onScanFailed(errorCode);
            }
        };
    }
    /**
     * Device scan callback for below lollipop device.
     */
    private void initScanCallbackSupport() {
        if (mLeScanCallback != null) return;
        this.mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                mBluetoothDevices.add(device);
                mBleEventBus.post(new DiscoveredDevicesEvent(device, mBluetoothDevices));
            }
        };
    }



    private void scanLeDevice(final boolean enable) {
        if (enable) {
            startScanning();
        } else {
            stopScanning();
        }
    }

    private void startScanning() {
        mHandler = new Handler();
        // Stops scanning after a
        //... pre-defined scan period.
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScanning();
            }
        }, SCAN_PERIOD);

        mScanning = true;
//        mBluetoothAdapter.startLeScan(mLeScanCallback);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            try {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                ScanSettings settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                mLEScanner.startScan(null, settings, mScanCallback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mBleEventBus.post(new ScanningEvent(mScanning));
    }

    private void stopScanning() {
        mScanning = false;
//        mBluetoothAdapter.stopLeScan(mLeScanCallback);
//        mBleEventBus.post(new ScanningEvent(false));
//        DeviceDiscoveryService.this.stopSelf();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        } else {
            try {
                mLEScanner.stopScan(mScanCallback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mBleEventBus.post(new ScanningEvent(false));
        DeviceDiscoveryService.this.stopSelf();
    }


    /*private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    mBluetoothDevices.add(device);
                    mBleEventBus.post(new DiscoveredDevicesEvent(device, mBluetoothDevices));
                }
            };*/

    @Produce
    public DiscoveredDevicesEvent produceAnswer() {
        return new DiscoveredDevicesEvent(null, mBluetoothDevices);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopScanning();
        mBleEventBus.unregister(this);
    }

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