package com.pavle.patternswitch.activities;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.pavle.patternswitch.R;
import com.pavle.patternswitch.adapter.DeviceAdapter;
import com.pavle.patternswitch.adapter.PatternAdapter;
import com.pavle.patternswitch.bluetooth.BleWrapper;
import com.pavle.patternswitch.bluetooth.BleWrapperCallbacks;
import com.pavle.patternswitch.global.Global;
import com.pavle.patternswitch.objects.Device;
import com.pavle.patternswitch.objects.Trigger;

import java.util.ArrayList;

/**
 * Created by Pavle on 24.5.2015..
 */
public class CreatePatternActivity extends Activity implements AdapterView.OnItemClickListener {

    private final static int REQUEST_ENABLE_BT = 1;
    private static final long SCANNING_TIMEOUT = 3 * 1000; /* 3 seconds */

    private Context mContext;
    private Activity mActivity;
    private BleWrapper BleWrapper = null;
    private ArrayList<Device> mDeviceList;
    private Handler mHandler;
    private DeviceAdapter mDeviceAdapter;


    private boolean mScanning;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivity_create_pattern);

        mContext = this;
        mActivity = this;
        mDeviceList = new ArrayList<>();
        mHandler = new Handler();

        /*Before all, if bluetooth is off, ask to turn it on */
        BleWrapper = new BleWrapper(this, new BleWrapperCallbacks.NullAdapter() {
            public void uiDeviceFound(final BluetoothDevice device, final int rssi, final byte[] record) {
                handleFoundDevice(device, rssi, record);
            }
        });
        mDeviceAdapter = new DeviceAdapter(mContext, R.layout.list_item_device, mDeviceList);
    }

    private void handleFoundDevice(BluetoothDevice device, int rssi, byte[] record) {
        if (mDeviceList.contains(device) == false && mDeviceList != null && device.getName().contains("RTRK")) {
            for(Device d:mDeviceList){
                if(d.getDevice().getName().equals(device.getName())){
                    return;
                }
            }
            mDeviceList.add(new Device(device, rssi, record));
            //displayDevices();
        }
    }

    private void displayDevices() {
        final ListView lvTriggerDevices = (ListView) findViewById(R.id.lvChooseTriggerDevice);
        lvTriggerDevices.setOnItemClickListener(this);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                lvTriggerDevices.setAdapter(mDeviceAdapter);
            }
        });
    }




    @Override
    protected void onResume() {
        super.onResume();
        // on every Resume check if BT is enabled (user could turn it off while app was in background etc.)
        if (BleWrapper.isBtEnabled() == false) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            // see onActivityResult to check what is the status of our request
        }
        BleWrapper.initialize();

        if (mDeviceList != null) {
            mDeviceList.clear();
        } else {

        }
        // Automatically start scanning for devices
        mScanning = true;
        // remember to add timeout for scanning to not run it forever and drain the battery
        addScanningTimeout();
        BleWrapper.startScanning();

    }
    @Override
    protected void onPause() {
        super.onPause();

        mScanning = false;
        BleWrapper.stopScanning();
        mDeviceList.clear();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mScanning = false;
        BleWrapper.stopScanning();
        mDeviceList.clear();
    }

    /* make sure that potential scanning will take no longer
  * than <SCANNING_TIMEOUT> seconds from now on */
    private void addScanningTimeout() {
        Runnable timeout = new Runnable() {
            @Override
            public void run() {
                if (BleWrapper == null) return;
                mScanning = false;
                BleWrapper.stopScanning();
                displayDevices();
            }
        };
        mHandler.postDelayed(timeout, SCANNING_TIMEOUT);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Device d = mDeviceList.get(position);
        Trigger t = new Trigger();
        t.setTriggerDeviceName(d.getDevice().getName());
        Global.setDeviceList(mDeviceList);
        Global.setTriggerDevelopment(t);
        Intent i = new Intent(CreatePatternActivity.this,CreatePatternActivity1.class);
        startActivity(i);
        this.finish();
    }

    @Override
    public void onBackPressed() {
        Intent i = new Intent(CreatePatternActivity.this,CreateActivity.class);
        startActivity(i);
        this.finish();
    }
}
