package com.ericsson.uecontrol.core.logic;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import com.ericsson.uecontrol.gui.MainActivity;
import org.apache.log4j.Logger;

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

/**
 * Created by ezivkoc on 2015-01-19.
 */
public class UeBehaviourSynchronize extends UeBehaviour {
    private static final Logger log = Logger.getLogger(UeBehaviourSynchronize.class);
    private final String SERVICE_UUID = "5ef27dac-a003-11e4-89d3-123b93f75cba";

    @Override
    protected void execute() throws Exception {
        log.debug("Terminating execution");
        super.getExecutor().setNextBehaviour(0);
        log.debug("Resetting executor");
        super.getExecutor().reset();
        Thread.sleep(VISUAL_SLEEP_PERIOD); // Sleep as a visual queue
    }


    @Override
    public String getName() {
        return "Synchronize";
    }

    @Override
    public String toString() {
        return "Will stop synchronize with a remote device";
    }


class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            BluetoothAdapter mBluetoothAdapter = BluetoothUtil.getAdapter();
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("uecontrol", UUID.fromString(SERVICE_UUID));
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

    public void run() {
        try {
            BluetoothSocket socket = null;
            // Keep listening until exception occurs or a socket is returned
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    break;
                }
                // If a connection was accepted
                if (socket != null) {
                    // Do work to manage the connection (in a separate thread)
                    manageConnectedSocket(socket);
                    mmServerSocket.close();
                    break;
                }
            }
        }catch (Exception e){
            log.trace(null, e);
        }
    }

    private void manageConnectedSocket(BluetoothSocket socket) {

    }

    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }



}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(SERVICE_UUID));
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        BluetoothAdapter mBluetoothAdapter = BluetoothUtil.getAdapter();
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        manageConnectedSocket(mmSocket);
    }

    private void manageConnectedSocket(BluetoothSocket mmSocket) {

    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }





}
}


class BluetoothUtil{
    public static BluetoothAdapter getAdapter(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                ((Activity)MainActivity.getContext()).startActivityForResult(enableBtIntent, 1515);
            }
        }
        return mBluetoothAdapter;
    }

    public static void getPairedDevices(){
        BluetoothAdapter mBluetoothAdapter = getAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        // If there are paired devices
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                //log.debug("Paired: " + device.getName() + "\n" + device.getAddress());
            }
        }
    }

    public static void discover(){
        // Create a BroadcastReceiver for ACTION_FOUND
        final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // When discovery finds a device
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // Get the BluetoothDevice object from the Intent
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // Add the name and address to an array adapter to show in a ListView
                    //log.debug("Discovered: "+device.getName() + "\n" + device.getAddress());
                }
            }
        };
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        MainActivity.getContext().registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
    }

    public void setDiscoverable(){
        Intent discoverableIntent = new
                Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        MainActivity.getContext().startActivity(discoverableIntent);
    }
}