package net.sadaji.pressure;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private SensorManager manager;
    private SensorEventListener listener;
    private List list;
    private Sensor pressure;
    private double hectoPascal;
    DataView m_dataView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        m_dataView = new DataView(this);
        setContentView(m_dataView);
        //Timer
        final Handler handler = new Handler();
        final Runnable run = new Runnable() {
            @Override
            public void run() {
                // UIスレッド
                handler.postDelayed(this, 200);
                m_dataView.invalidate();
            }
        };
        handler.post(run);

        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        list = manager.getSensorList(Sensor.TYPE_PRESSURE);
        listener = new SensorEventListener() {
            public void onSensorChanged(SensorEvent event) {
                hectoPascal = (double)event.values[0];
            }

            public void onAccuracyChanged(Sensor sensor, int accuracy) {}
            };
    }



    @Override
    protected void onResume() {
        // Register a listener for the sensor.
        super.onResume();

        if (list.size() > 0) {
            manager.registerListener(listener, (Sensor)list.get(0),
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onPause() {
        // Be sure to unregister the sensor when the activity pauses.
        super.onPause();
        manager.unregisterListener(listener,(Sensor) list.get(0));
    }

    public double getPressure(){
        return hectoPascal;
    }
}