package com.example.mountaintravel.service;

import java.util.List;
import java.util.Map;

import com.example.mountaintravel.util.AppJsonFileReader;
import com.smart.gtstrvl.OriginalityActivity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

@SuppressLint("NewApi")
public class BlueService extends Service {
	int blecount = -1;

	public BlueService() {
		super();
	}
	private BluetoothAdapter mBluetoothAdapter;
	private boolean mScanning;
	private static final long SCAN_PERIOD = 1000000000;
	String code = "";
	private static Handler handler;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		Log.d("TAG", "buleService  is  Starting !");
		parseblue("bluetooth.json");
		initBle();
		bule();
	}

	public static void startSevice(Context c) {
		handler = ((OriginalityActivity) c).getHandler();
		if (handler == null) {
			Log.d("TAG", "SDAD");
		}
		Intent in = new Intent(c, BlueService.class);
		c.startService(in);

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d("TAG", "buleService  onDestroy !");
		scanLeDevice(false);// 蓝牙功能

	}

	public void bule() {
		// 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
		if (!mBluetoothAdapter.isEnabled()) {
			if (!mBluetoothAdapter.isEnabled()) {
				@SuppressWarnings("unused")
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				mBluetoothAdapter.enable(); // 强制开启蓝牙
				// mBluetoothAdapter.disable();
			}
		}
		if (mBluetoothAdapter.isEnabled()) {
			scanLeDevice(true);// 蓝牙功能
		}
	}
	@SuppressLint("NewApi")
	public void initBle() {
		mHandler = new Handler();
		// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
		if (!getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(this, "该设备不支持蓝牙!", Toast.LENGTH_SHORT).show();
			return;
		}
		// 初始化 Bluetooth adapter,通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
		final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		
		// 检查设备上是否支持蓝牙
//		if (mBluetoothAdapter == null) {
//			// 强制开启蓝牙
//			mBluetoothAdapter.enable();
//			// Toast.makeText(this, "没有搜索到其他设备！", Toast.LENGTH_SHORT).show();
//			return;
//		}
	}

	@SuppressLint("NewApi")
	private void scanLeDevice(final boolean enable) {
		if (enable) { // Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {
				@SuppressLint("NewApi")
				@Override
				public void run() {
					mScanning = false;
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
				}
			}, SCAN_PERIOD);
			mScanning = true;
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			if (device.getAddress() != null) {
				String address = device.getAddress().replace(":", "");
				//System.out.println(address);
				// if (blecount != bleIndex(address)) {
				for (int i = 0; i < scenicBluetooth.size(); i++) {
					for (String key : scenicBluetooth.get(i).keySet()) {
						if (address.equals(key)) {
							blecount = i;// 获得当前蓝牙发射器
							code = scenicBluetooth.get(i).get(address);// 蓝牙信标对应的景点name
							Message msg = new Message();
							msg.obj = code;
							handler.sendMessage(msg);
							// System.out.println("第  \t"+i+" device.getAddress()=: "
							// +address+"\t name=: "+name);
							break;
						}
					}
				}
			}
		}
	};

	public int bleIndex(String name) {
		for (int i = 0; i < scenicBluetooth.size(); i++) {
			for (String key : scenicBluetooth.get(i).keySet()) {
				if (name.equals(key)) {
					return i;
				}
			}
		}
		return 0;
	}

	public void parseblue(String name) {
		String jsonStr = AppJsonFileReader.getJson(getBaseContext(), name);
		scenicBluetooth = AppJsonFileReader.bluetoothJson(jsonStr);
	}

	private Handler mHandler;
	private List<Map<String, String>> scenicBluetooth;

}
