package net.heartshield.prevent;

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

import net.heartshield.control.ReleaseConfig;
import net.heartshield.control.IMeasurementController;
import net.heartshield.data.AppInfo;
import net.heartshield.data.DataManagerFactory;
import net.heartshield.data.IMeasurementDataManager;
import net.heartshield.data.MeasurementMeta;
import net.heartshield.data.UserMeta;
import net.heartshield.signal.DVec;
import net.heartshield.signal.IVec;
import net.heartshield.ui.PermissionHelper;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Home screen showing the logo and big menu buttons.
 *
 * @author David Madl (git@abanbytes.eu)
 * @date 2016-04-01
 */
public class HomeActivity extends Activity {
    private static final String TAG = "HomeActivity";

    private PermissionHelper mPermissions;
    private IMeasurementDataManager mDataManager;
    private boolean mFirstOpen = true;

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

        // TODO: catch RuntimeError for external storage unavailable, show error dialog explaining the trouble
        String appId = AppInfo.getInstance(this).getAppMeta().appId;

        TextView ver = (TextView) findViewById(R.id.versionText);
        MessageFormat fmt = new MessageFormat(getResources().getString(BuildConfig.DEBUG ? R.string.version_debug : R.string.version_release));
        ver.setText(fmt.format(new Object[]{BuildConfig.VERSION_NAME, BuildConfig.GIT_HASH, appId}));

        mPermissions = new PermissionHelper(this, ReleaseConfig.PERMISSIONS);
        mPermissions.request();
    }

    public void measure(View view) {
        if(AppInfo.getInstance(this).devSettings.skipDialogs) {
            // if skipDialogs is set in dev settings, jump straight to measurement, assuming 25 male
            Intent intent = new Intent(HomeActivity.this, MeasureActivity.class);
            intent.putExtra("meta", new UserMeta(25, UserMeta.Gender.MALE, 1.96));
            startActivity(intent);
            return;
        }

        Intent intent = new Intent(HomeActivity.this, EnterAgeActivity.class);
        intent.putExtra("mode", IMeasurementController.MeasurementMode.RISK);
        startActivity(intent);
    }

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

    public void stetho(View view) {
        // Alexis or David only.
        //if(AppInfo.getInstance(this).getAppMeta().appId.equals("9189008E") || BuildConfig.BUILD_TYPE.equals("debug")) {
        if(true) {
            //Intent intent = new Intent(HomeActivity.this, MeasureActivity.class);
            //Intent intent = new Intent(HomeActivity.this, BreatheActivity.class);

            Intent intent = new Intent(HomeActivity.this, EnterAgeActivity.class);
            //intent.putExtra("mode", IMeasurementController.MeasurementMode.RISK);
            //startActivity(intent);
            
            //intent.putExtra("mode", IMeasurementController.MeasurementMode.VITAL_CHECK);
            intent.putExtra("mode", IMeasurementController.MeasurementMode.SWEEP_BREATHING);
            intent.putExtra("meta", new UserMeta(0, null, null));
            startActivity(intent);
        } else {
            // ignore (since PcgActivity returns immediately)
            Intent intent = new Intent(HomeActivity.this, PcgActivity.class);
            startActivity(intent);
        }
    }

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

    private List<Double> mLogoClicks = new ArrayList<>();
    public void logoClick(View view) {
        // tapping icon for developer options only works in Debug builds
        if(!BuildConfig.DEBUG)
            return;

        mLogoClicks.add(System.nanoTime() / 1e9);

        final int NUM_TAPS = 8;
        final double MAX_DT = 0.3;
        if(mLogoClicks.size() < NUM_TAPS)
            return;

        double[] sp = DVec.toArray(mLogoClicks);
        boolean tapsUnlocked = IVec.all(DVec.lt(DVec.diff(DVec.get(sp, sp.length - NUM_TAPS, sp.length)), DVec.mul(DVec.ones(NUM_TAPS-1), MAX_DT)));
        if(tapsUnlocked) {
            Intent intent = new Intent(HomeActivity.this, DevSettingsActivity.class);
            startActivity(intent);
        }
    }

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

        // for background sync
        mDataManager = DataManagerFactory.getInstance().getDataManager(this);

        if(mFirstOpen) {
            // only show sync hint Toasts on first open (otherwise, it is quite annoying every time you return to home screen)
            mDataManager.setSyncListener(new IMeasurementDataManager.SyncListener() {
                @Override
                public void onProgress(int synced, int candidates) {
                    if(synced == 0 && candidates > 0) {
                        Toast.makeText(HomeActivity.this, "Syncing " + candidates + " measurements...", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFinished(int synced, int candidates) {

                }
            });
        }
        mDataManager.startBackgroundThread();
        mDataManager.startBackgroundSync();

        mFirstOpen = false;
    }

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