package com.uhf288.scanlable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.rfid.trans.ReaderParameter;
import com.rfid.trans.UHFLib;

import java.io.IOException;
import java.util.UUID;

public class ConnectBluetooth extends Activity implements View.OnClickListener {
    private final static int REQUEST_CONNECT_DEVICE = 1;
    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    private TextView bOpen;
    private static final int MSG_CONNECT_SUCCESS = 0;
    private static final int MSG_CONNECT_FAILED = 1;
    BluetoothDevice _device = null;
    private static Handler mHandler;
    BluetoothSocket _socket=null;
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect_bluetooth);
        if (_bluetooth == null){
            Toast.makeText(this,getString(R.string.str_open_bt_first), Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        new Thread(){
            public void run(){
                if(_bluetooth.isEnabled()==false){
                    _bluetooth.enable();
                }
            }
        }.start();

        bOpen = (TextView)findViewById(R.id.textview_connectbluetooth);
        bOpen.setOnClickListener(this);

        mHandler = new Handler(){
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_CONNECT_SUCCESS:
                        Intent intent;
                        intent = new Intent().setClass(ConnectBluetooth.this, MainActivity.class);
                        startActivity(intent);
                        break;
                    case MSG_CONNECT_FAILED:
                        Toast.makeText(getApplication(),getString(R.string.openport_failed), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        };

    }

    @Override
    public void onClick(View view) {
        if(view == bOpen){
            if(_bluetooth.isEnabled()==false){
                Toast.makeText(this, getString(R.string.str_open_bt), Toast.LENGTH_LONG).show();
                return;
            }
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case REQUEST_CONNECT_DEVICE:

                if (resultCode == Activity.RESULT_OK) {

                    String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

                    _device = _bluetooth.getRemoteDevice(address);

                    Thread mThread = new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            try{
                                _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
                            }catch(IOException e){
                                mHandler.removeMessages(MSG_CONNECT_FAILED);
                                mHandler.sendEmptyMessage(MSG_CONNECT_FAILED);
                                return;
                            }
                            if(_socket==null)
                            {
                                mHandler.removeMessages(MSG_CONNECT_FAILED);
                                mHandler.sendEmptyMessage(MSG_CONNECT_FAILED);
                                return;
                            }
                            Reader.rrlib = new UHFLib(2,"");
                            byte[]data = new byte[1];
                            ReaderParameter param = Reader.rrlib.GetInventoryParameter();
                            param.ComAddr = (byte)255;
                            Reader.rrlib.SetInventoryParameter(param);
                            int result = Reader.rrlib.Connect("", 0,_socket);
                            if(result==0)
                            {
                                param.Session=254;
                                param.QValue = 6;
                                param.reTryCount = 4;
                                Reader.rrlib.SetInventoryParameter(param);
                                mHandler.removeMessages(MSG_CONNECT_SUCCESS);
                                mHandler.sendEmptyMessage(MSG_CONNECT_SUCCESS);
                            }
                            else
                            {
                                mHandler.removeMessages(MSG_CONNECT_FAILED);
                                mHandler.sendEmptyMessage(MSG_CONNECT_FAILED);
                            }
                        }
                    });
                    mThread.start();
                }
                break;
            default:break;
        }
    }
}