package com.pavle.patternswitch.activities;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.pavle.patternswitch.R;
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 CreatePatternActivity1 extends Activity implements AdapterView.OnItemClickListener,BleWrapperCallbacks {

    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 mBleWrapper = null;
    private ArrayList<Device> mDeviceList;
    private Handler mHandler;
    private Device mSelctedDevice;
    private TextView mRSSItv;

    private int mRSSISum = 0;
    private boolean mGetRssiValue = false;
    private int mRSSICounter = 0;

    private boolean mScanning;

    private RadioButton rbGoingTo;
    private RadioButton rbComingFrom;



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

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



        mRSSItv = (TextView) findViewById(R.id.tvCreatePattern1RSSI);
        rbGoingTo = (RadioButton) findViewById(R.id.rbGoingTo);
        rbComingFrom = (RadioButton) findViewById(R.id.rbComingFrom);
        rbGoingTo.setChecked(true); //by default, so that we are sure that one rb is definitely selected

        final Button btnCreatePatternActivity1 = (Button) findViewById(R.id.btnCreatePattern1);
        btnCreatePatternActivity1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mSelctedDevice != null){
                    btnCreatePatternActivity1.setEnabled(false);
                    mBleWrapper.setRSSISamplingTime(100);
                    mGetRssiValue = true;
                    mRSSICounter = 0;
                    mRSSISum = 0;
                    CountDownTimer ct = new CountDownTimer(5000, 1000) {
                        @Override
                        public void onTick(final long millisUntilFinished) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(mContext,String.valueOf(millisUntilFinished/1000),Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFinish() {
                            Trigger t = Global.getTriggerDevelopment();
                            t.setDistance((mRSSISum) / mRSSICounter);
                            t.setGoingTo(rbGoingTo.isChecked() ? Trigger.GOING_TO : Trigger.COMING_FROM);

                            Global.setTriggerDevelopment(t);

                            BleWrapper.setRSSISamplingTime(1500);
                            mBleWrapper.stopMonitoringRssiValue();
                            mBleWrapper.disconnect();


                            Intent i = new Intent(CreatePatternActivity1.this,CreateInteractionActivity.class);
                            startActivity(i);
                            CreatePatternActivity1.this.finish();
                        }
                    };
                    ct.start();
                }
                else{
                    Toast.makeText(mContext,"You're disconnected from the device",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void handleFoundDevice(BluetoothDevice device, int rssi, byte[] record) {
        String name = Global.getTriggerDevelopment().getTriggerDeviceName();
        if (device.getName().equals(name)) {
            mSelctedDevice = new Device(device,rssi,record);
            mRSSItv.setText("Distance: "+String.valueOf(rssi));
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(mBleWrapper == null) mBleWrapper = new BleWrapper(this, this);

        // on every Resume check if BT is enabled (user could turn it off while app was in background etc.)
        if(mBleWrapper.isBtEnabled() == false) {
            // BT is not turned on - ask user to make it enabled
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            // see onActivityResult to check what is the status of our request
        }

        if(mBleWrapper.initialize() == false) {
            finish();
        }

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

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

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

    @Override
    protected void onStop() {
        super.onStop();
        mScanning = false;
        mBleWrapper.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 (mBleWrapper == null) return;
                mScanning = false;
                mBleWrapper.stopScanning();
            }
        };
        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(CreatePatternActivity1.this,CreatePatternActivity1.class);
        startActivity(i);
    }

    @Override
    public void uiDeviceFound(final BluetoothDevice device,final int rssi,final byte[] record) {
        String name = Global.getTriggerDevelopment().getTriggerDeviceName();
        if (device.getName().equals(name)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mBleWrapper.createHandler();
                    mBleWrapper.connect(device.getAddress());
                    mSelctedDevice = new Device(device,rssi,record);

                }
            });
        }
    }

    @Override
    public void uiDeviceConnected() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "connected", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void uiDeviceDisconnected() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "disconnected", Toast.LENGTH_SHORT).show();
            }
        });
        mSelctedDevice = null;
    }

    @Override
    public void uiAvailableServices(boolean success) {

    }

    @Override
    public void uiCharacteristicsForServices(boolean success) {

    }

    @Override
    public void uiNotificationsSet(boolean success) {

    }

    @Override
    public void uiNewRssiAvailable(BluetoothGatt gatt, BluetoothDevice device, final int rssi) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(mGetRssiValue){
                        mRSSISum += rssi;
                        mRSSICounter++;
                    }
                    else {
                        mRSSItv.setText("Distance: " + String.valueOf(rssi));
                    }
                }
            });
    }

    @Override
    public void uiNewValueForCharacteristic(BluetoothGatt gatt, BluetoothDevice device, BluetoothGattService service, BluetoothGattCharacteristic ch, String strValue, int intValue, byte[] rawValue, String timestamp) {

    }

    @Override
    public void uiGotNotification(BluetoothGatt gatt, BluetoothDevice device, BluetoothGattService service, BluetoothGattCharacteristic characteristic) {

    }

    @Override
    public void uiSuccessfulWrite(BluetoothGatt gatt, BluetoothDevice device, BluetoothGattService service, BluetoothGattCharacteristic ch, String description) {

    }

    @Override
    public void uiFailedWrite(BluetoothGatt gatt, BluetoothDevice device, BluetoothGattService service, BluetoothGattCharacteristic ch, String description) {

    }

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