package com.ecom.park_jy;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class start_btdevice extends Activity {
    public static String EXTRA_DEVICE_ADDRESS = "dev";
    private ArrayAdapter<String> mPairedDevices;
    private ArrayAdapter<String> mNewDevices;
    private BluetoothAdapter adapter;
    private BluetoothDevice device;
    private BluetoothSocket socket;
    OutputStream output;
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    IntentFilter filter = new IntentFilter();
    Button btn;
    bt_socket bts = new bt_socket();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_btdevice);
        setResult(Activity.RESULT_CANCELED);
        btn = (Button) findViewById(R.id.button3);
        adapter = BluetoothAdapter.getDefaultAdapter();

        mPairedDevices = new ArrayAdapter<String>(this, R.layout.bt_text);
        mNewDevices = new ArrayAdapter<String>(this, R.layout.bt_text);

        ListView pairDv = (ListView) findViewById(R.id.list_item);
        pairDv.setAdapter(mPairedDevices);
        pairDv.setOnItemClickListener(mDv);

        ListView newDv = (ListView) findViewById(R.id.list_item2);
        newDv.setAdapter(mNewDevices);
        newDv.setOnItemClickListener(mDv);

        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        System.out.println("filter-=>"+filter);         //測試回報
        this.registerReceiver(receiver, filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        System.out.println("filter-=>"+filter);         //測試回報
        this.registerReceiver(receiver, filter);

        adapter = BluetoothAdapter.getDefaultAdapter();

        Set<BluetoothDevice> pairdevice = adapter.getBondedDevices();
        if (pairdevice.size() > 0) {
            findViewById(R.id.textView2).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairdevice) {
                mPairedDevices.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            String nodevice = "未找到印表機";
            mPairedDevices.add(nodevice);
        }
        setProgressBarIndeterminateVisibility(true);
        setTitle("搜尋中...");
        findViewById(R.id.textView2).setVisibility(View.VISIBLE);
    }

    public void bt_scan(View v) {
        setProgressBarIndeterminateVisibility(true);
        setTitle("搜尋中...");
        findViewById(R.id.textView2).setVisibility(View.VISIBLE);

        if (adapter.isDiscovering()) {
            adapter.cancelDiscovery();
            btn.setText("搜尋設備");
        } else {
            adapter.startDiscovery();
            btn.setText("停止搜尋");
        }
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevices.add(device.getName() + "\n" + device.getAddress());
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminate(false);
                setTitle("選擇設備");
                if (mNewDevices.getCount() == 0) {
                    String nodv = "未找到設備";
                    mNewDevices.add(nodv);
                }
            }
        }
    };

    private AdapterView.OnItemClickListener mDv = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            adapter.cancelDiscovery();
            String info = ((TextView) view).getText().toString();
            String address = info.substring(info.length() - 17);
            device = adapter.getRemoteDevice(address);
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
            if (output == null) {
                run();
                bts.setSocket(socket);
            }
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };

    public void run() {
        adapter.cancelDiscovery();
        try {
            socket = device.createRfcommSocketToServiceRecord(uuid);
            socket.connect();
            output = socket.getOutputStream();
            Toast.makeText(this, "連接成功~~~", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                socket.close();
                Toast.makeText(this, "連接失敗...", Toast.LENGTH_LONG).show();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return;
        }
    }

}
