package net.heartshield.prevent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import net.heartshield.control.IMeasurementController;
import net.heartshield.data.AppInfo;
import net.heartshield.data.IMeasurementDataManager;
import net.heartshield.data.MeasurementDataManager;
import net.heartshield.data.UserMeta;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author David Madl (git@abanbytes.eu)
 * @date 2017-06-08
 */
public class EnterGenderActivity extends Activity {
    private static final String TAG = "EnterGenderActivity";

    private IMeasurementDataManager mDataManager;
    private Timer mConnTimer;

    private ToggleImageButton mMale;
    private ToggleImageButton mFemale;
    private FancyButton mStartButton;
    private ImageView mConnection;
    private UserMeta mUser;
    private IMeasurementController.MeasurementMode mMode;

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

        mDataManager = MeasurementDataManager.getInstance(getApplicationContext());

        mMale = (ToggleImageButton) findViewById(R.id.toggleMale);
        mFemale = (ToggleImageButton) findViewById(R.id.toggleFemale);
        mConnection = (ImageView) findViewById(R.id.connection);
        mStartButton = (FancyButton) findViewById(R.id.startButton);
        mStartButton.setEnabled(false);

        postConnImage(0);

        mMale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleGender(v);
            }
        });
        mFemale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleGender(v);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        startTimer();

        mMode = (IMeasurementController.MeasurementMode) getIntent().getSerializableExtra("mode");

        mUser = (UserMeta) getIntent().getSerializableExtra("meta");
        if(mUser == null)
            throw new IllegalStateException("expect to come from EnterAgeActivity together with age");

        if(mUser.gender != null) {
            // maybe we can guess the gender from before
            ToggleImageButton button = (mUser.gender == UserMeta.Gender.MALE) ? mMale : mFemale;
            button.setPressed(true);
            toggleGender(button);
        }
    }

    public void toggleGender(View view) {
        Log.i(TAG, "toggleGender(view=" + view + ") called");
        ToggleImageButton button = (ToggleImageButton) view;
        ToggleImageButton other = (button == mMale) ? mFemale : mMale;
        if(button.getPressed())
            other.setPressed(false);

        mStartButton.setEnabled(mMale.getPressed() || mFemale.getPressed());
    }

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

    private static final int CONN_UPDATE_INTERVAL_MS = 5000;

    private void startTimer() {
        if(mConnTimer == null) {
            mConnTimer = new Timer();
            mConnTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    updateConnectionDisplay();
                }
            }, CONN_UPDATE_INTERVAL_MS, CONN_UPDATE_INTERVAL_MS);
        }
    }

    private void stopTimer() {
        if(mConnTimer != null) {
            mConnTimer.cancel();
            mConnTimer = null;
        }
    }

    public void updateConnectionDisplay() {
        String appId = AppInfo.getInstance(this).getAppMeta().appId;
        mDataManager.ping(appId, new IMeasurementDataManager.PingResultListener() {
            @Override
            public void onResult() {
                postConnImage(R.drawable.connection_ok);
            }

            @Override
            public void onError() {
                postConnImage(R.drawable.connection_nok);
            }
        });
    }

    private void postConnImage(final int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mConnection.setImageResource(resId);
                mConnection.invalidate();
            }
        });
    }

    private UserMeta.Gender getGender() {
        if(mMale.getPressed())
            return UserMeta.Gender.MALE;
        else if(mFemale.getPressed())
            return UserMeta.Gender.FEMALE;
        else
            return null;
    }

    public void start(View view) {
        final boolean breathing = mMode.equals(IMeasurementController.MeasurementMode.PACED_BREATHING) || mMode.equals(IMeasurementController.MeasurementMode.SWEEP_BREATHING);
        Intent intent = new Intent(EnterGenderActivity.this, breathing ? BreatheActivity.class : MeasureActivity.class);
        mUser.gender = getGender();
        intent.putExtra("meta", mUser);
        intent.putExtra("mode", mMode);
        startActivity(intent);
    }

    public void stats(View view) {
        Intent intent = new Intent(EnterGenderActivity.this, ResultListActivity.class);
        startActivity(intent);
    }

    public void stetho(View view) {
        Intent intent = new Intent(EnterGenderActivity.this, PcgActivity.class);
        startActivity(intent);
    }

    public void help(View view) {
        Intent intent = new Intent(EnterGenderActivity.this, DisclaimerActivity.class);
        intent.putExtra("forceShow", true);
        startActivity(intent);
    }
}
