package net.heartshield.prevent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.TextureView;
import android.view.View;
import android.widget.Toast;

import net.heartshield.control.Device;
import net.heartshield.control.IMeasurementController;
import net.heartshield.control.MeasurementController;
import net.heartshield.data.UserMeta;
import net.heartshield.sensors.IntensityDetector;
import net.heartshield.sensors.SensorFactory;

/**
 *
 * TODO: FailActivity is a duplicate of PlaceActivity. Not quite ideal.
 *
 * @author David Madl (git@abanbytes.eu)
 * @date 2017-05-26
 */
public class PlaceActivity extends Activity {
    private UserMeta mUser;
    private IMeasurementController mController;
    private TextureView mCameraPreview;
    private FancyButton mStartButton;

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

        mCameraPreview = (TextureView) findViewById(R.id.cameraPreview);
        mStartButton = (FancyButton) findViewById(R.id.startButton);

        // disable by default until camera signal looks good enough
        mStartButton.setEnabled(false);

        mController = new MeasurementController(getMainLooper(), new Device(this), new SensorFactory(this), mCameraPreview);
        mController.setListener(mListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUser = (UserMeta) getIntent().getSerializableExtra("meta");

        mController.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            mController.stop();
        } catch (IMeasurementController.FramesDroppedException e) {
            e.printStackTrace();
        }
    }

    public void next(View view) {
        Intent intent = new Intent(PlaceActivity.this, RelaxActivity.class);
        intent.putExtra("meta", mUser);
        startActivity(intent);
    }

    private IMeasurementController.Listener mListener = new IMeasurementController.Listener() {
        @Override
        public void onState(IMeasurementController.State state) {
            if(state.equals(IMeasurementController.State.SAMPLING)) {
                // nice
                mStartButton.setEnabled(true);
            } else if(state.equals(IMeasurementController.State.WAITING)) {
                // wait
                mStartButton.setEnabled(false);
            } else if(state.equals(IMeasurementController.State.FAILED)) {
                Toast.makeText(PlaceActivity.this, "Camera failed", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFrame(double timeSinceStart, double timeSinceLock, double[] rgb, IntensityDetector.ImageSummary summary) {

        }
    };
}
