导航菜单

页面标题

页面副标题

xDrip+ v04633772025.07.16 - Home.java 源代码

正在查看: xDrip+ v04633772025.07.16 应用的 Home.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.eveningoutpost.dexdrip;

import android.R;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.eveningoutpost.dexdrip.BestGlucose;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.calibrations.NativeCalibrationPipe;
import com.eveningoutpost.dexdrip.calibrations.PluggableCalibration;
import com.eveningoutpost.dexdrip.cloud.backup.BackupActivity;
import com.eveningoutpost.dexdrip.dagger.Injectors;
import com.eveningoutpost.dexdrip.databinding.ActivityHomeBinding;
import com.eveningoutpost.dexdrip.databinding.ActivityHomeShelfSettingsBinding;
import com.eveningoutpost.dexdrip.databinding.PopupInitialStatusHelperBinding;
import com.eveningoutpost.dexdrip.eassist.EmergencyAssistActivity;
import com.eveningoutpost.dexdrip.g5model.DexSyncKeeper;
import com.eveningoutpost.dexdrip.g5model.DexTimeKeeper;
import com.eveningoutpost.dexdrip.g5model.Ob1G5StateMachine;
import com.eveningoutpost.dexdrip.g5model.SensorDays;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.driver.UsbId;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.util.HexDump;
import com.eveningoutpost.dexdrip.insulin.Insulin;
import com.eveningoutpost.dexdrip.insulin.InsulinManager;
import com.eveningoutpost.dexdrip.insulin.MultipleInsulins;
import com.eveningoutpost.dexdrip.insulin.inpen.InPenEntry;
import com.eveningoutpost.dexdrip.insulin.pendiq.Pendiq;
import com.eveningoutpost.dexdrip.models.ActiveBgAlert;
import com.eveningoutpost.dexdrip.models.ActiveBluetoothDevice;
import com.eveningoutpost.dexdrip.models.BgReading;
import com.eveningoutpost.dexdrip.models.BloodTest;
import com.eveningoutpost.dexdrip.models.Calibration;
import com.eveningoutpost.dexdrip.models.HeartRate;
import com.eveningoutpost.dexdrip.models.InsulinInjection;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.models.LibreBlock;
import com.eveningoutpost.dexdrip.models.ProcessInitialDataQuality;
import com.eveningoutpost.dexdrip.models.Sensor;
import com.eveningoutpost.dexdrip.models.StepCounter;
import com.eveningoutpost.dexdrip.models.Treatments;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.nfc.NFControl;
import com.eveningoutpost.dexdrip.profileeditor.DatePickerFragment;
import com.eveningoutpost.dexdrip.profileeditor.ProfileAdapter;
import com.eveningoutpost.dexdrip.services.ActivityRecognizedService;
import com.eveningoutpost.dexdrip.services.DexCollectionService;
import com.eveningoutpost.dexdrip.services.Ob1G5CollectionService;
import com.eveningoutpost.dexdrip.services.PlusSyncService;
import com.eveningoutpost.dexdrip.services.WixelReader;
import com.eveningoutpost.dexdrip.ui.BaseShelf;
import com.eveningoutpost.dexdrip.ui.MicroStatus;
import com.eveningoutpost.dexdrip.ui.MicroStatusImpl;
import com.eveningoutpost.dexdrip.ui.NumberGraphic;
import com.eveningoutpost.dexdrip.ui.UiPing;
import com.eveningoutpost.dexdrip.ui.dialog.ChooseInsulinPenDialog;
import com.eveningoutpost.dexdrip.ui.dialog.DidYouCancelAlarm;
import com.eveningoutpost.dexdrip.ui.dialog.HeyFamUpdateOptInDialog;
import com.eveningoutpost.dexdrip.ui.dialog.QuickSettingsDialogs;
import com.eveningoutpost.dexdrip.ui.graphic.ITrendArrow;
import com.eveningoutpost.dexdrip.ui.graphic.TrendArrowFactory;
import com.eveningoutpost.dexdrip.utilitymodels.AlertPlayer;
import com.eveningoutpost.dexdrip.utilitymodels.BgGraphBuilder;
import com.eveningoutpost.dexdrip.utilitymodels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.utilitymodels.ColorCache;
import com.eveningoutpost.dexdrip.utilitymodels.CompatibleApps;
import com.eveningoutpost.dexdrip.utilitymodels.Experience;
import com.eveningoutpost.dexdrip.utilitymodels.Inevitable;
import com.eveningoutpost.dexdrip.utilitymodels.JamorhamShowcaseDrawer;
import com.eveningoutpost.dexdrip.utilitymodels.MockDataSource;
import com.eveningoutpost.dexdrip.utilitymodels.NanoStatus;
import com.eveningoutpost.dexdrip.utilitymodels.NightscoutUploader;
import com.eveningoutpost.dexdrip.utilitymodels.Notifications;
import com.eveningoutpost.dexdrip.utilitymodels.PersistentStore;
import com.eveningoutpost.dexdrip.utilitymodels.Pref;
import com.eveningoutpost.dexdrip.utilitymodels.PrefsViewImpl;
import com.eveningoutpost.dexdrip.utilitymodels.SendFeedBack;
import com.eveningoutpost.dexdrip.utilitymodels.ShotStateStore;
import com.eveningoutpost.dexdrip.utilitymodels.SourceWizard;
import com.eveningoutpost.dexdrip.utilitymodels.StatusLine;
import com.eveningoutpost.dexdrip.utilitymodels.UndoRedo;
import com.eveningoutpost.dexdrip.utilitymodels.UpdateActivity;
import com.eveningoutpost.dexdrip.utilitymodels.VoiceCommands;
import com.eveningoutpost.dexdrip.utils.ActivityWithMenu;
import com.eveningoutpost.dexdrip.utils.BgToSpeech;
import com.eveningoutpost.dexdrip.utils.DatabaseUtil;
import com.eveningoutpost.dexdrip.utils.DexCollectionType;
import com.eveningoutpost.dexdrip.utils.DisplayQRCode;
import com.eveningoutpost.dexdrip.utils.LibreTrendGraph;
import com.eveningoutpost.dexdrip.utils.Preferences;
import com.eveningoutpost.dexdrip.utils.SdcardImportExport;
import com.eveningoutpost.dexdrip.utils.TestFeature;
import com.eveningoutpost.dexdrip.wearintegration.Amazfitservice;
import com.eveningoutpost.dexdrip.wearintegration.WatchUpdaterService;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import lecho.lib.hellocharts.gesture.ChartTouchHandler;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.ViewportChangeListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PreviewLineChartView;

public class Home extends ActivityWithMenu {
    private static Activity mActivity;
    private static ShowcaseView myShowcase;
    private static String nexttoast;
    private BroadcastReceiver _broadcastReceiver;
    private boolean alreadyDisplayedBgInfoCommon;
    public BgGraphBuilder bgGraphBuilder;
    private ActivityHomeBinding binding;
    private Button bpmButton;
    private ImageButton btnApprove;
    private ImageButton btnBloodGlucose;
    private ImageButton btnCancel;
    private ImageButton btnCarbohydrates;
    private ImageButton[] btnInsulinDose;
    private ImageButton btnNote;
    private ImageButton btnRedo;
    private ImageButton btnSpeak;
    private ImageButton btnTime;
    private ImageButton btnUndo;
    private ImageButton btnVehicleMode;
    private ImageButton buttonInsulinSingleDose;
    boolean carbsset;
    public LineChartView chart;
    private boolean checkedeula;
    private TextView currentBgValueText;
    private TextView dexbridgeBattery;
    public AlertDialog dialog;
    private String display_delta;
    NanoStatus expiryStatus;
    private TextView extraStatusLineText;
    boolean glucoseset;
    private AlertDialog helper_dialog;
    public Viewport holdViewport;
    BaseShelf homeShelf;
    private ProcessInitialDataQuality.InitialDataQuality initialDataQuality;
    private PopupInitialStatusHelperBinding initial_status_binding;
    ArrayList<Insulin> insulins;
    boolean[] insulinset;
    boolean insulinsumset;
    private boolean isBTShare;
    private boolean isG5Share;
    private boolean is_newbie;
    private ITrendArrow itr;
    private long lastDataTick;
    private long lastViewPortPan;
    public final int maxInsulinProfiles;
    MicroStatus microStatus;
    NanoStatus nanoStatus;
    private BroadcastReceiver newDataReceiver;
    private TextView notificationText;
    private TextView parakeetBattery;
    private PreviewLineChartView previewChart;
    private boolean recognitionRunning;
    private boolean screen_forced_on;
    private wordDataWrapper searchWords;
    private TextView sensorAge;
    private boolean small_height;
    private boolean small_screen;
    private boolean small_width;
    private BroadcastReceiver statusReceiver;
    private AlertDialog status_helper_dialog;
    private Button stepsButton;
    private Viewport tempViewport;
    private TextView textBloodGlucose;
    private TextView textCarbohydrates;
    private TextView[] textInsulinDose;
    private TextView textInsulinSumDose;
    private TextView textTime;
    double thisInsulinSumNumber;
    double thiscarbsnumber;
    double thisglucosenumber;
    double[] thisinsulinnumber;
    Insulin[] thisinsulinprofile;
    double thisnumber;
    double thistimeoffset;
    String thisuuid;
    String thisword;
    boolean timeset;
    private final UiPing ui;
    private boolean updateStuff;
    private boolean updatingChartViewport;
    private boolean updatingPreviewViewport;
    private TextView voiceRecognitionText;
    boolean watchkeypad;
    long watchkeypad_timestamp;
    boolean watchkeypadset;
    private static final String TAG = "jamorham " + Home.class.getSimpleName();
    public static boolean activityVisible = false;
    public static boolean invalidateMenu = false;
    public static boolean blockTouches = false;
    private static boolean is_follower = false;
    private static boolean is_follower_set = false;
    private static boolean is_holo = true;
    private static boolean reset_viewport = false;
    private static double last_speech_time = BgReading.BESTOFFSET;
    private static float hours = 2.5f;
    private static boolean has_libreblock = false;
    private static boolean has_libreblock_set = false;
    private static volatile String statusIOB = "";
    private static volatile String statusBWP = "";

    class wordData {
        public String lexicon;
        public ArrayList<String> matchWords;
    }

    public static void lambda$parakeetSetupMode$44(DialogInterface dialogInterface, int i) {
    }

    public Home() {
        this.maxInsulinProfiles = MultipleInsulins.isEnabled() ? 3 : 0;
        this.ui = new UiPing();
        this.updatingPreviewViewport = false;
        this.updatingChartViewport = false;
        this.screen_forced_on = false;
        this.tempViewport = new Viewport();
        this.holdViewport = new Viewport();
        this.btnInsulinDose = new ImageButton[3];
        this.textInsulinDose = new TextView[3];
        this.alreadyDisplayedBgInfoCommon = false;
        this.recognitionRunning = false;
        this.display_delta = "";
        this.small_width = false;
        this.small_height = false;
        this.small_screen = false;
        this.thisnumber = -1.0d;
        this.thisglucosenumber = BgReading.BESTOFFSET;
        this.thiscarbsnumber = BgReading.BESTOFFSET;
        this.thisInsulinSumNumber = BgReading.BESTOFFSET;
        this.thisinsulinnumber = new double[3];
        this.thisinsulinprofile = new Insulin[3];
        this.insulins = null;
        this.thistimeoffset = BgReading.BESTOFFSET;
        this.thisword = "";
        this.thisuuid = "";
        this.carbsset = false;
        this.insulinset = new boolean[3];
        this.insulinsumset = false;
        this.glucoseset = false;
        this.timeset = false;
        this.watchkeypad = false;
        this.watchkeypadset = false;
        this.watchkeypad_timestamp = -1L;
        this.searchWords = null;
    }

    @Override
    @SuppressLint({"ObsoleteSdkInt"})
    protected void onCreate(Bundle bundle) {
        mActivity = this;
        if (!xdrip.checkAppContext(getApplicationContext())) {
            toast(xdrip.gs(2131756943));
            Log.wtf(TAG, "xdrip.checkAppContext FAILED!");
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException unused) {
            }
            if (!xdrip.checkAppContext(getApplicationContext())) {
                toast(xdrip.gs(2131755288));
                finish();
            }
        }
        xdrip.checkForcedEnglish(this);
        super.onCreate(bundle);
        setTheme(2131820554);
        Injectors.getHomeShelfComponent().inject(this);
        if (!Experience.gotData()) {
            this.homeShelf.set("source_wizard", true);
            this.homeShelf.set("source_wizard_auto", true);
        }
        this.nanoStatus = new NanoStatus("collector", 1000);
        this.expiryStatus = new NanoStatus("s-expiry", 15000);
        set_is_follower();
        setVolumeControlStream(3);
        this.checkedeula = checkEula();
        ActivityHomeBinding inflate = ActivityHomeBinding.inflate(getLayoutInflater());
        this.binding = inflate;
        inflate.setVs(this.homeShelf);
        this.binding.setHome(this);
        this.binding.setUi(this.ui);
        this.binding.setNano(this.nanoStatus);
        this.binding.setExpiry(this.expiryStatus);
        setContentView(this.binding.getRoot());
        Toolbar toolbar = (Toolbar) findViewById(2131296797);
        setSupportActionBar(toolbar);
        toolbar.setLongClickable(true);
        toolbar.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public final boolean onLongClick(View view) {
                boolean lambda$onCreate$0;
                lambda$onCreate$0 = Home.this.lambda$onCreate$0(this, view);
                return lambda$onCreate$0;
            }
        });
        this.dexbridgeBattery = (TextView) findViewById(2131297057);
        this.parakeetBattery = (TextView) findViewById(2131296834);
        this.sensorAge = (TextView) findViewById(2131296708);
        this.extraStatusLineText = (TextView) findViewById(2131296610);
        this.currentBgValueText = (TextView) findViewById(2131296525);
        this.bpmButton = (Button) findViewById(2131296402);
        this.stepsButton = (Button) findViewById(2131297191);
        this.extraStatusLineText.setText("");
        this.dexbridgeBattery.setText("");
        this.parakeetBattery.setText("");
        this.sensorAge.setText("");
        if (BgGraphBuilder.isXLargeTablet(getApplicationContext())) {
            this.currentBgValueText.setTextSize(100.0f);
        }
        this.notificationText = (TextView) findViewById(2131296816);
        if (BgGraphBuilder.isXLargeTablet(getApplicationContext())) {
            this.notificationText.setTextSize(40.0f);
        }
        this.is_newbie = Experience.isNewbie();
        if (this.checkedeula && Experience.installedForAtLeast(300000L)) {
            checkBatteryOptimization();
        }
        this.voiceRecognitionText = (TextView) findViewById(2131297144);
        this.textBloodGlucose = (TextView) findViewById(2131297056);
        this.textCarbohydrates = (TextView) findViewById(2131297058);
        this.textInsulinSumDose = (TextView) findViewById(2131297063);
        this.textTime = (TextView) findViewById(2131297068);
        this.btnBloodGlucose = (ImageButton) findViewById(2131296396);
        this.btnCarbohydrates = (ImageButton) findViewById(2131296453);
        this.textInsulinDose[0] = (TextView) findViewById(2131297060);
        this.buttonInsulinSingleDose = (ImageButton) findViewById(2131296454);
        this.btnInsulinDose[0] = (ImageButton) findViewById(2131296455);
        this.textInsulinDose[1] = (TextView) findViewById(2131297061);
        this.btnInsulinDose[1] = (ImageButton) findViewById(2131296456);
        this.textInsulinDose[2] = (TextView) findViewById(2131297062);
        this.btnInsulinDose[2] = (ImageButton) findViewById(2131296457);
        this.btnCancel = (ImageButton) findViewById(2131296480);
        this.btnApprove = (ImageButton) findViewById(2131296367);
        this.btnTime = (ImageButton) findViewById(2131297119);
        this.btnUndo = (ImageButton) findViewById(2131296416);
        this.btnRedo = (ImageButton) findViewById(2131296414);
        this.btnVehicleMode = (ImageButton) findViewById(2131297169);
        hideAllTreatmentButtons();
        if (this.searchWords == null) {
            initializeSearchWords("");
        }
        if (this.insulins == null) {
            this.insulins = InsulinManager.getDefaultInstance();
        }
        ImageButton imageButton = (ImageButton) findViewById(2131296415);
        this.btnSpeak = imageButton;
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$1(view);
            }
        });
        this.btnSpeak.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public final boolean onLongClick(View view) {
                boolean lambda$onCreate$2;
                lambda$onCreate$2 = Home.this.lambda$onCreate$2(view);
                return lambda$onCreate$2;
            }
        });
        ImageButton imageButton2 = (ImageButton) findViewById(2131296413);
        this.btnNote = imageButton2;
        imageButton2.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public final boolean onLongClick(View view) {
                boolean lambda$onCreate$3;
                lambda$onCreate$3 = Home.this.lambda$onCreate$3(view);
                return lambda$onCreate$3;
            }
        });
        this.btnNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$4(view);
            }
        });
        this.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$5(view);
            }
        });
        this.buttonInsulinSingleDose.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$6(view);
            }
        });
        for (final int i = 0; i < this.maxInsulinProfiles; i++) {
            this.btnInsulinDose[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Home.this.textInsulinDose[i].setVisibility(4);
                    Home.this.btnInsulinDose[i].setVisibility(4);
                    Home home = Home.this;
                    double[] dArr = home.thisinsulinnumber;
                    int i2 = i;
                    Treatments.create(BgReading.BESTOFFSET, dArr[i2], Treatments.convertLegacyDoseToInjectionListByName(home.thisinsulinprofile[i2].getName(), Home.this.thisinsulinnumber[i]), Treatments.getTimeStampWithOffset(Home.this.thistimeoffset));
                    Home home2 = Home.this;
                    double[] dArr2 = home2.thisinsulinnumber;
                    int i3 = i;
                    dArr2[i3] = 0.0d;
                    home2.insulinset[i3] = false;
                    home2.textInsulinDose[i].setText("");
                    boolean unused2 = Home.reset_viewport = true;
                    if (Home.this.hideTreatmentButtonsIfAllDone()) {
                        Home.this.updateCurrentBgInfo("insulin button");
                    }
                }
            });
        }
        this.btnApprove.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$7(view);
            }
        });
        this.btnCarbohydrates.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$8(view);
            }
        });
        this.btnBloodGlucose.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$9(view);
            }
        });
        this.btnTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$onCreate$10(view);
            }
        });
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int i2 = displayMetrics.widthPixels;
        int i3 = displayMetrics.heightPixels;
        if (i2 <= 320) {
            this.small_width = true;
            this.small_screen = true;
        }
        if (i3 <= 320) {
            this.small_height = true;
            this.small_screen = true;
        }
        Log.d(TAG, "Width height: " + i2 + " " + i3 + " DPI:" + displayMetrics.densityDpi);
        JoH.fixActionBar(this);
        try {
            getSupportActionBar().setTitle(2131755147);
        } catch (NullPointerException unused2) {
            Log.e(TAG, "Couldn't set title due to null pointer");
        }
        activityVisible = true;
        this.statusReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String stringExtra = intent.getStringExtra("bwp");
                if (stringExtra != null) {
                    String unused3 = Home.statusBWP = stringExtra;
                    Home.this.refreshStatusLine();
                    return;
                }
                String stringExtra2 = intent.getStringExtra("iob");
                if (stringExtra2 != null) {
                    String unused4 = Home.statusIOB = stringExtra2;
                    Home.this.refreshStatusLine();
                }
            }
        };
        processIncomingBundle(getIntent().getExtras());
        checkBadSettings();
        PlusSyncService.startSyncService(getApplicationContext(), "HomeOnCreate");
        ParakeetHelper.notifyOnNextCheckin(false);
        if (this.checkedeula && !getString(2131755147).equals("xDrip+")) {
            showcasemenu(7);
        }
        this.currentBgValueText.setText("");
    }

    public boolean lambda$onCreate$0(Home home, View view) {
        ActivityHomeShelfSettingsBinding inflate = ActivityHomeShelfSettingsBinding.inflate(getLayoutInflater());
        Dialog dialog = new Dialog(home);
        dialog.requestWindowFeature(1);
        inflate.setVs(this.homeShelf);
        inflate.setHome(home);
        this.homeShelf.set("arrow_configurator", false);
        dialog.setContentView(inflate.getRoot());
        dialog.show();
        return false;
    }

    public void lambda$onCreate$1(View view) {
        promptTextInput();
    }

    public boolean lambda$onCreate$2(View view) {
        promptSpeechInput();
        return true;
    }

    public boolean lambda$onCreate$3(View view) {
        if (Pref.getBooleanDefaultFalse("default_to_voice_notes")) {
            showNoteTextInputDialog(view, 0L);
            return false;
        }
        promptSpeechNoteInput(view);
        return false;
    }

    public void lambda$onCreate$4(View view) {
        if (!Pref.getBooleanDefaultFalse("default_to_voice_notes")) {
            showNoteTextInputDialog(view, 0L);
        } else {
            promptSpeechNoteInput(view);
        }
    }

    public void lambda$onCreate$5(View view) {
        cancelTreatment();
    }

    public void lambda$onCreate$6(View view) {
        this.textInsulinSumDose.setVisibility(4);
        this.buttonInsulinSingleDose.setVisibility(4);
        Treatments.create(BgReading.BESTOFFSET, this.thisInsulinSumNumber, Treatments.getTimeStampWithOffset(this.thistimeoffset));
        Pendiq.handleTreatment(this.thisInsulinSumNumber);
        this.thisInsulinSumNumber = BgReading.BESTOFFSET;
        reset_viewport = true;
        if (hideTreatmentButtonsIfAllDone()) {
            updateCurrentBgInfo("insulin button");
        }
    }

    public void lambda$onCreate$7(View view) {
        processAndApproveTreatment();
    }

    public void lambda$onCreate$8(View view) {
        this.textCarbohydrates.setVisibility(4);
        this.btnCarbohydrates.setVisibility(4);
        reset_viewport = true;
        Treatments.create(this.thiscarbsnumber, BgReading.BESTOFFSET, new ArrayList(), Treatments.getTimeStampWithOffset(this.thistimeoffset));
        this.thiscarbsnumber = BgReading.BESTOFFSET;
        if (hideTreatmentButtonsIfAllDone()) {
            updateCurrentBgInfo("carbs button");
        }
    }

    public void lambda$onCreate$9(View view) {
        reset_viewport = true;
        processCalibration();
    }

    public void lambda$onCreate$10(View view) {
        this.textTime.setVisibility(4);
        this.btnTime.setVisibility(4);
        if (hideTreatmentButtonsIfAllDone()) {
            updateCurrentBgInfo("time button");
        }
    }

    private boolean firstRunDialogs(boolean z) {
        if (!z || !this.is_newbie) {
            return true;
        }
        AlertDialog alertDialog = this.dialog;
        if (alertDialog != null && alertDialog.isShowing()) {
            return true;
        }
        Experience.processSteps(this);
        return true;
    }

    private boolean checkBatteryOptimization() {
        final String packageName = getPackageName();
        if (((PowerManager) getSystemService("power")).isIgnoringBatteryOptimizations(packageName) || Pref.getBooleanDefaultFalse("requested_ignore_battery_optimizations_new") || xdrip.isRunningTest()) {
            return true;
        }
        Log.d(TAG, "Requesting ignore battery optimization");
        AlertDialog alertDialog = this.dialog;
        if ((alertDialog == null || !alertDialog.isShowing()) && PersistentStore.incrementLong("asked_battery_optimization") < 40000) {
            JoH.show_ok_dialog(this, xdrip.gs(2131756012), xdrip.gs(2131757058), new Runnable() {
                @Override
                public void run() {
                    try {
                        Intent intent = new Intent();
                        intent.setAction("android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS");
                        intent.setData(Uri.parse("package:" + packageName));
                        Home.this.startActivityForResult(intent, 1996);
                    } catch (ActivityNotFoundException unused) {
                        JoH.static_toast_short(Home.this.getString(2131755904));
                        UserError.Log.wtf(Home.TAG, "Device does not appear to support battery optimization whitelisting!");
                    }
                }
            });
            return false;
        }
        JoH.static_toast_long(xdrip.gs(2131756611));
        return false;
    }

    public void refreshStatusLine() {
        String str;
        try {
            StringBuilder sb = new StringBuilder();
            String str2 = "";
            if (statusIOB.length() > 0) {
                str = "IoB: " + statusIOB;
            } else {
                str = "";
            }
            sb.append(str);
            if (statusBWP.length() > 0) {
                str2 = " " + statusBWP;
            }
            sb.append(str2);
            String sb2 = sb.toString();
            Log.d(TAG, "Refresh Status Line: " + sb2);
            getSupportActionBar().setSubtitle(sb2);
        } catch (NullPointerException e) {
            Log.e(TAG, "Could not set subtitle due to null pointer exception: " + e);
        }
    }

    public static void updateStatusLine(String str, String str2) {
        Intent intent = new Intent("com.eveningoutpost.dexdrip.HOME_STATUS_ACTION");
        intent.putExtra(str, str2);
        LocalBroadcastManager.getInstance(xdrip.getAppContext()).sendBroadcast(intent);
        Log.d(TAG, "Home Status update: " + str + " / " + str2);
    }

    private void checkBadSettings() {
        if (Pref.getBoolean("predictive_bg", false)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(xdrip.gs(2131756311));
            builder.setMessage(xdrip.gs(2131757084));
            builder.setPositiveButton(xdrip.gs(2131757078), new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    Home.this.lambda$checkBadSettings$11(dialogInterface, i);
                }
            });
            builder.setNegativeButton(2131755911, new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.create().show();
        }
    }

    public void lambda$checkBadSettings$11(DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        Pref.setBoolean("predictive_bg", false);
        toast(xdrip.gs(2131756306));
    }

    private synchronized void processFingerStickCalibration(double d, double d2, boolean z) {
        JoH.clearCache();
        String str = TAG;
        UserError.Log.uel(str, "Processing Finger stick Calibration with values: glucose: " + d + " timeoffset: " + d2 + " full auto: " + z);
        if (d > BgReading.BESTOFFSET) {
            if (d2 < BgReading.BESTOFFSET) {
                toaststaticnext(xdrip.gs(2131755638));
                return;
            }
            final Intent intent = new Intent(getApplicationContext(), (Class<?>) AddCalibration.class);
            intent.setFlags(268435456);
            intent.putExtra("timestamp", JoH.tsl());
            intent.putExtra("bg_string", JoH.qs(d));
            intent.putExtra("bg_age", Long.toString((long) (d2 / 1000.0d)));
            intent.putExtra("allow_undo", "true");
            intent.putExtra("cal_source", "processFingerStringCalibration");
            Log.d(str, "processFingerStickCalibration number: " + d + " offset: " + d2);
            if (!z) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(String.format(xdrip.gs(2131756972), JoH.qs(d, 1)));
                builder.setMessage(xdrip.gs(2131755479));
                builder.setPositiveButton(xdrip.gs(2131757072), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.lambda$processFingerStickCalibration$13(intent, dialogInterface, i);
                    }
                });
                builder.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.create().show();
            } else if (PersistentStore.getDouble("last-auto-calibration-value") == d) {
                UserError.Log.wtf(str, "Rejecting auto calibration as it is the same as last: " + d);
            } else {
                PersistentStore.setDouble("last-auto-calibration-value", d);
                Log.d(str, "Proceeding with calibration intent without asking");
                startIntentThreadWithDelayedRefresh(intent);
            }
        }
    }

    public static void lambda$processFingerStickCalibration$13(Intent intent, DialogInterface dialogInterface, int i) {
        intent.putExtra("note_only", "false");
        intent.putExtra("from_interactive", "true");
        startIntentThreadWithDelayedRefresh(intent);
        dialogInterface.dismiss();
    }

    private void processCalibrationNoUI(double d, double d2) {
        if (d > BgReading.BESTOFFSET) {
            if (d2 < BgReading.BESTOFFSET) {
                toaststaticnext(xdrip.gs(2131755638));
                return;
            }
            final Intent intent = new Intent(getApplicationContext(), (Class<?>) AddCalibration.class);
            intent.setFlags(268435456);
            intent.putExtra("timestamp", JoH.tsl());
            intent.putExtra("bg_string", JoH.qs(d));
            intent.putExtra("bg_age", Long.toString((long) (d2 / 1000.0d)));
            intent.putExtra("allow_undo", "true");
            intent.putExtra("cal_source", "processCalibrationNoUi");
            String str = TAG;
            Log.d(str, "ProcessCalibrationNoUI number: " + d + " offset: " + d2);
            String string = Pref.getString("treatment_fingerstick_calibration_usage", "ask");
            Log.d(str, "Creating blood test record from input data");
            BloodTest.createFromCal(d, d2, "Manual Entry");
            GcmActivity.syncBloodTests();
            if (Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations_auto")) {
                return;
            }
            if (string.equals("ask")) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(xdrip.gs(2131756961));
                builder.setMessage(xdrip.gs(2131755478));
                builder.setPositiveButton(xdrip.gs(2131757072), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.lambda$processCalibrationNoUI$15(intent, dialogInterface, i);
                    }
                });
                builder.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.create().show();
                return;
            }
            if (string.equals("auto")) {
                if (Pref.getBooleanDefaultFalse("bluetooth_meter_for_calibrations_auto") || DexCollectionType.getDexCollectionType() == DexCollectionType.Follower || !JoH.pratelimit("ask_about_auto_calibration", 2592000)) {
                    return;
                }
                AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
                builder2.setTitle(xdrip.gs(2131755497));
                builder2.setMessage(xdrip.gs(2131755531));
                builder2.setPositiveButton(xdrip.gs(2131757076), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.lambda$processCalibrationNoUI$17(dialogInterface, i);
                    }
                });
                builder2.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder2.create().show();
                return;
            }
            if (string.equals("never")) {
                return;
            }
            intent.putExtra("note_only", string.equals("never") ? "true" : "false");
            startIntentThreadWithDelayedRefresh(intent);
        }
    }

    public static void lambda$processCalibrationNoUI$15(Intent intent, DialogInterface dialogInterface, int i) {
        intent.putExtra("note_only", "false");
        intent.putExtra("from_interactive", "true");
        startIntentThreadWithDelayedRefresh(intent);
        dialogInterface.dismiss();
    }

    public static void lambda$processCalibrationNoUI$17(DialogInterface dialogInterface, int i) {
        Pref.setBoolean("bluetooth_meter_for_calibrations_auto", true);
        JoH.static_toast_long(xdrip.gs(2131755180));
        dialogInterface.dismiss();
    }

    static void startIntentThreadWithDelayedRefresh(final Intent intent) {
        new Thread() {
            @Override
            public void run() {
                xdrip.getAppContext().startActivity(intent);
                Home.staticRefreshBGCharts();
            }
        }.start();
        JoH.runOnUiThreadDelayed(new Home$$ExternalSyntheticLambda11(), 4000L);
    }

    private void processCalibration() {
        processCalibrationNoUI(this.thisglucosenumber, this.thistimeoffset);
        this.textBloodGlucose.setVisibility(4);
        this.btnBloodGlucose.setVisibility(4);
        if (hideTreatmentButtonsIfAllDone()) {
            updateCurrentBgInfo("bg button");
        }
    }

    private void cancelTreatment() {
        hideAllTreatmentButtons();
        WatchUpdaterService.sendWearToast(xdrip.gs(2131756904), 0);
    }

    private void processAndApproveTreatment() {
        double d;
        Insulin insulin;
        double d2;
        Insulin insulin2;
        double d3 = this.thisglucosenumber;
        double d4 = this.thistimeoffset;
        if (this.watchkeypad) {
            long j = this.watchkeypad_timestamp - ((long) d4);
            d4 = JoH.tsl() - j;
            String str = TAG;
            Log.d(str, "Watch Keypad timestamp is: " + JoH.dateTimeText(j) + " Original offset: " + JoH.qs(this.thistimeoffset) + " New: " + JoH.qs(d4));
            if (d4 > 2.592E8d || d4 < -1.08E7d) {
                Log.e(str, "Treatment timestamp out of range: " + d4);
                JoH.static_toast_long(xdrip.gs(2131756911));
                WatchUpdaterService.sendWearLocalToast(xdrip.gs(2131756907), 1);
            } else {
                JoH.static_toast_long(xdrip.gs(2131756910));
                WatchUpdaterService.sendWearLocalToast(xdrip.gs(2131756910), 1);
                long timeStampWithOffset = Treatments.getTimeStampWithOffset(d4);
                if (Treatments.byTimestamp(timeStampWithOffset) == null) {
                    ArrayList arrayList = new ArrayList();
                    for (int i = 0; i < this.maxInsulinProfiles; i++) {
                        if (this.insulinset[i] && (insulin2 = this.thisinsulinprofile[i]) != null) {
                            arrayList.add(new InsulinInjection(insulin2, this.thisinsulinnumber[i]));
                        }
                    }
                    Log.d(TAG, "processAndApproveTreatment create watchkeypad Treatment carbs=" + this.thiscarbsnumber + " insulin=" + this.thisInsulinSumNumber + " timestamp=" + JoH.dateTimeText(timeStampWithOffset) + " uuid=" + this.thisuuid);
                    Treatments.create(this.thiscarbsnumber, this.thisInsulinSumNumber, arrayList, timeStampWithOffset, this.thisuuid);
                    if (MultipleInsulins.isEnabled() && arrayList.size() > 1) {
                        Iterator it = arrayList.iterator();
                        d2 = BgReading.BESTOFFSET;
                        while (it.hasNext()) {
                            InsulinInjection insulinInjection = (InsulinInjection) it.next();
                            if (insulinInjection.getProfile() == InsulinManager.getBolusProfile()) {
                                d2 = insulinInjection.getUnits();
                            }
                        }
                    } else {
                        d2 = this.thisInsulinSumNumber;
                    }
                    Pendiq.handleTreatment(d2);
                } else {
                    Log.d(str, "processAndApproveTreatment Treatment already exists carbs=" + this.thiscarbsnumber + " insulin=" + this.thisInsulinSumNumber + " timestamp=" + JoH.dateTimeText(timeStampWithOffset));
                }
            }
        } else {
            WatchUpdaterService.sendWearToast(xdrip.gs(2131756910), 1);
            ArrayList arrayList2 = new ArrayList();
            for (int i2 = 0; i2 < this.maxInsulinProfiles; i2++) {
                if (this.insulinset[i2] && (insulin = this.thisinsulinprofile[i2]) != null) {
                    arrayList2.add(new InsulinInjection(insulin, this.thisinsulinnumber[i2]));
                }
            }
            Treatments.create(this.thiscarbsnumber, this.thisInsulinSumNumber, arrayList2, Treatments.getTimeStampWithOffset(d4));
            if (MultipleInsulins.isEnabled() && arrayList2.size() > 1) {
                Iterator it2 = arrayList2.iterator();
                d = BgReading.BESTOFFSET;
                while (it2.hasNext()) {
                    InsulinInjection insulinInjection2 = (InsulinInjection) it2.next();
                    if (insulinInjection2.getProfile() == InsulinManager.getBolusProfile()) {
                        d = insulinInjection2.getUnits();
                    }
                }
            } else {
                d = this.thisInsulinSumNumber;
            }
            Pendiq.handleTreatment(d);
        }
        hideAllTreatmentButtons();
        if (hideTreatmentButtonsIfAllDone()) {
            updateCurrentBgInfo("approve button");
        }
        if (this.watchkeypad) {
            if (d3 > BgReading.BESTOFFSET) {
                if (d4 > 2.592E8d || d4 < -1.08E7d) {
                    Log.e(TAG, "Treatment bloodtest timestamp out of range: " + d4);
                } else {
                    BloodTest.createFromCal(d3, d4, "Manual Entry", this.thisuuid);
                }
            }
            this.watchkeypad = false;
            this.watchkeypadset = false;
            this.watchkeypad_timestamp = -1L;
        } else {
            processCalibrationNoUI(d3, d4);
        }
        staticRefreshBGCharts();
    }

    private void processIncomingBundle(Bundle bundle) {
        String str = TAG;
        Log.d(str, "Processing incoming bundle");
        if (bundle != null) {
            String string = bundle.getString("/xdrip_plus_voice_payload");
            if (string != null) {
                this.voiceRecognitionText.setText(string);
                this.voiceRecognitionText.setVisibility(0);
                last_speech_time = JoH.ts();
                naturalLanguageRecognition(string);
            }
            if (bundle.getString("/xdrip_plus_approve_treatment") != null || this.watchkeypad) {
                processAndApproveTreatment();
                return;
            }
            if (bundle.getString("/xdrip_plus_cancel_treatment") != null) {
                cancelTreatment();
                return;
            }
            if (bundle.getString("START_APP_SPEECH_RECOGNITION") != null) {
                promptSpeechInput();
                return;
            }
            if (bundle.getString("START_APP_TEXT_RECOGNITION") != null) {
                promptTextInput_old();
                return;
            }
            if (bundle.getString("CREATE_TREATMENT_NOTE") != null) {
                try {
                    showNoteTextInputDialog(null, Long.parseLong(bundle.getString("CREATE_TREATMENT_NOTE")), JoH.tolerantParseDouble(bundle.getString("CREATE_TREATMENT_NOTE2"), BgReading.BESTOFFSET));
                    return;
                } catch (NullPointerException unused) {
                    Log.d(TAG, "Got null point exception during CREATE_TREATMENT_NOTE Intent");
                    return;
                } catch (NumberFormatException e) {
                    JoH.static_toast_long(xdrip.gs(2131755947) + e);
                    return;
                }
            }
            if (bundle.getString("HOME_FULL_WAKEUP") != null) {
                if (!JoH.isScreenOn()) {
                    final PowerManager.WakeLock wakeLock = JoH.getWakeLock("full-wakeup", 61000);
                    keepScreenOn();
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Home.this.dontKeepScreenOn();
                            JoH.releaseWakeLock(wakeLock);
                            Home.this.finish();
                        }
                    }, 60000L);
                    return;
                }
                Log.d(str, "Screen is already on so not turning on");
                return;
            }
            if (bundle.getString("GCM_RESOLUTION_ACTIVITY") != null) {
                GcmActivity.checkPlayServices(this, this);
                return;
            }
            if (bundle.getString("SNOOZE_CONFIRM_DIALOG") != null) {
                GcmActivity.sendSnoozeToRemoteWithConfirm(this);
                return;
            }
            if (bundle.getString("SHOW_NOTIFICATION") != null) {
                Intent intent = new Intent(this, (Class<?>) Home.class);
                int i = bundle.getInt("notification_id");
                if (i == 4912 && (!Sensor.isActive() || BgReading.last() != null)) {
                    Log.e(str, "Sensor not in warm up period when notification due to fire");
                    return;
                } else {
                    JoH.showNotification(bundle.getString("SHOW_NOTIFICATION"), bundle.getString("notification_body"), PendingIntent.getActivity(this, 0, intent, 134217728), i, true, true, true);
                    UserError.Log.uel(str, bundle.getString("notification_body"));
                    return;
                }
            }
            boolean z = true;
            if (bundle.getString("BLUETOOTH_METER_CALIBRATION") != null) {
                try {
                    double d = JoH.tolerantParseDouble(bundle.getString("BLUETOOTH_METER_CALIBRATION"), BgReading.BESTOFFSET);
                    double d2 = JoH.tolerantParseDouble(bundle.getString("BLUETOOTH_METER_CALIBRATION2"), -1.0d);
                    if (bundle.getString("BLUETOOTH_METER_CALIBRATION3") == null || !bundle.getString("BLUETOOTH_METER_CALIBRATION3").equals("auto")) {
                        z = false;
                    }
                    processFingerStickCalibration(d, d2, z);
                    return;
                } catch (NumberFormatException e2) {
                    JoH.static_toast_long(xdrip.gs(2131755947) + e2);
                    return;
                }
            }
            if (bundle.getString("ACTIVITY_SHOWCASE_INFO") != null) {
                showcasemenu(11);
                return;
            }
            if (bundle.getString("choice-intent") != null) {
                CompatibleApps.showChoiceDialog(this, (Intent) bundle.getParcelable("choice-intentx"));
                return;
            }
            if (bundle.getString("numberIconTest") != null) {
                JoH.show_ok_dialog(this, xdrip.gs(2131756144), xdrip.gs(2131755092), new Runnable() {
                    @Override
                    public final void run() {
                        Home.lambda$processIncomingBundle$19();
                    }
                });
                return;
            }
            if (bundle.getString("inpen-reset") != null) {
                InPenEntry.startWithReset();
                return;
            }
            if (bundle.getString("BLOOD_TEST_ACTION") != null) {
                Log.d(str, "BLOOD_TEST_ACTION");
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(xdrip.gs(2131755220));
                builder.setMessage(xdrip.gs(2131757033));
                String string2 = bundle.getString("BLOOD_TEST_ACTION2");
                if (string2 != null) {
                    final BloodTest byUUID = BloodTest.byUUID(string2);
                    if (byUUID == null) {
                        JoH.static_toast_long(String.format(xdrip.gs(2131755384), string2));
                        return;
                    }
                    builder.setNeutralButton(xdrip.gs(2131755931), new DialogInterface.OnClickListener() {
                        @Override
                        public final void onClick(DialogInterface dialogInterface, int i2) {
                            dialogInterface.dismiss();
                        }
                    });
                    builder.setPositiveButton(xdrip.gs(2131755258), new DialogInterface.OnClickListener() {
                        @Override
                        public final void onClick(DialogInterface dialogInterface, int i2) {
                            Home.lambda$processIncomingBundle$21(BloodTest.this, dialogInterface, i2);
                        }
                    });
                    builder.setNegativeButton(2131755418, new DialogInterface.OnClickListener() {
                        @Override
                        public final void onClick(DialogInterface dialogInterface, int i2) {
                            Home.lambda$processIncomingBundle$24(BloodTest.this, dialogInterface, i2);
                        }
                    });
                    builder.create().show();
                    return;
                }
                return;
            }
            if (bundle.getString("confirmsnooze") != null) {
                String string3 = bundle.getString("confirmsnooze");
                string3.hashCode();
                if (string3.equals("simpleconfirm")) {
                    DidYouCancelAlarm.dialog(this, new Runnable() {
                        @Override
                        public final void run() {
                            AlertPlayer.defaultSnooze();
                        }
                    });
                    return;
                }
                return;
            }
            if (bundle.getString("ENABLE_STREAMING_DIALOG") != null) {
                NFCReaderX.enableBluetoothAskUser(mActivity);
            } else if (bundle.getString("CHOOSE_INSULIN_PEN") != null) {
                ChooseInsulinPenDialog.show(this, bundle.getString("CHOOSE_INSULIN_PEN"));
            }
        }
    }

    public static void lambda$processIncomingBundle$19() {
        JoH.static_toast_long(xdrip.gs(2131756222));
        NumberGraphic.testNotification("123");
    }

    public static void lambda$processIncomingBundle$21(BloodTest bloodTest, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        startHomeWithExtra(xdrip.getAppContext(), "BLUETOOTH_METER_CALIBRATION", BgGraphBuilder.unitized_string_static(bloodTest.mgdl), Long.toString(JoH.msSince(bloodTest.timestamp)));
        bloodTest.addState(2L);
        GcmActivity.syncBloodTests();
    }

    public static void lambda$processIncomingBundle$24(final BloodTest bloodTest, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle(xdrip.gs(2131755368));
        builder.setMessage(xdrip.gs(2131755154));
        builder.setPositiveButton(xdrip.gs(2131757074), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface2, int i2) {
                Home.lambda$processIncomingBundle$22(BloodTest.this, dialogInterface2, i2);
            }
        });
        builder.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface2, int i2) {
                dialogInterface2.dismiss();
            }
        });
        builder.create().show();
    }

    public static void lambda$processIncomingBundle$22(BloodTest bloodTest, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        bloodTest.removeState(1L);
        NativeCalibrationPipe.removePendingCalibration((int) bloodTest.mgdl);
        GcmActivity.syncBloodTests();
        if (get_show_wear_treatments()) {
            BloodTest.pushBloodTestSyncToWatch(bloodTest, false);
        }
        staticRefreshBGCharts();
        JoH.static_toast_short(xdrip.gs(2131755423));
    }

    private void keepScreenOn() {
        this.screen_forced_on = true;
        JoH.runOnUiThread(new Runnable() {
            @Override
            public final void run() {
                Home.this.lambda$keepScreenOn$25();
            }
        });
    }

    public void lambda$keepScreenOn$25() {
        getWindow().addFlags(6815873);
    }

    public void dontKeepScreenOn() {
        JoH.runOnUiThread(new Runnable() {
            @Override
            public final void run() {
                Home.this.lambda$dontKeepScreenOn$26();
            }
        });
        this.screen_forced_on = false;
    }

    public void lambda$dontKeepScreenOn$26() {
        getWindow().clearFlags(6815873);
    }

    public static void startHomeWithExtra(Context context, String str, String str2) {
        startHomeWithExtra(context, str, str2, "");
    }

    public static void startHomeWithExtra(Context context, String str, String str2, String str3) {
        startHomeWithExtra(context, str, str2, str3, "");
    }

    public static void startHomeWithExtra(Context context, String str, String str2, String str3, String str4) {
        Intent intent = new Intent(context, (Class<?>) Home.class);
        intent.setFlags(268435456);
        intent.putExtra(str, str2);
        intent.putExtra(str + "2", str3);
        if (str4.length() > 0) {
            intent.putExtra(str + "3", str4);
        }
        Log.e("xxxxx", "calling startActivity");
        context.startActivity(intent);
    }

    public void cloudBackup(MenuItem menuItem) {
        JoH.startActivity(BackupActivity.class);
    }

    public void crowdTranslate(MenuItem menuItem) {
        startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://crowdin.com/project/xdrip")).addFlags(268435456));
    }

    public void testFeature(MenuItem menuItem) {
        TestFeature.testFeature1();
    }

    public void viewEventLog(MenuItem menuItem) {
        startActivity(new Intent(this, (Class<?>) EventLogActivity.class).setFlags(268435456).putExtra("events", ""));
    }

    public void ShowLibreTrend(MenuItem menuItem) {
        startActivity(new Intent(this, (Class<?>) LibreTrendGraph.class).setFlags(268435456).putExtra("events", ""));
    }

    public boolean hideTreatmentButtonsIfAllDone() {
        boolean z;
        int i = 0;
        while (true) {
            if (i >= this.maxInsulinProfiles) {
                z = true;
                break;
            }
            if (this.btnInsulinDose[i].getVisibility() != 4) {
                z = false;
                break;
            }
            i++;
        }
        if (this.btnBloodGlucose.getVisibility() != 4 || this.btnCarbohydrates.getVisibility() != 4 || !z) {
            return false;
        }
        hideAllTreatmentButtons();
        WatchUpdaterService.sendWearToast(xdrip.gs(2131756910), 1);
        return true;
    }

    private void hideAllTreatmentButtons() {
        this.textBloodGlucose.setVisibility(4);
        this.textCarbohydrates.setVisibility(4);
        this.btnApprove.setVisibility(4);
        this.btnCancel.setVisibility(4);
        this.btnCarbohydrates.setVisibility(4);
        this.textInsulinSumDose.setVisibility(4);
        for (int i = 0; i < 3; i++) {
            this.textInsulinDose[i].setVisibility(4);
            this.btnInsulinDose[i].setVisibility(4);
        }
        this.buttonInsulinSingleDose.setVisibility(4);
        this.btnBloodGlucose.setVisibility(4);
        this.voiceRecognitionText.setVisibility(4);
        this.textTime.setVisibility(4);
        this.btnTime.setVisibility(4);
        this.thiscarbsnumber = BgReading.BESTOFFSET;
        this.thisInsulinSumNumber = BgReading.BESTOFFSET;
        this.insulinsumset = false;
        for (int i2 = 0; i2 < 3; i2++) {
            Log.d(TAG, "INSULINSET: " + i2 + " " + this.thisinsulinnumber.length + " " + this.insulinset.length);
            this.thisinsulinnumber[i2] = 0.0d;
            this.insulinset[i2] = false;
        }
        this.thistimeoffset = BgReading.BESTOFFSET;
        this.thisglucosenumber = BgReading.BESTOFFSET;
        this.carbsset = false;
        this.glucoseset = false;
        this.timeset = false;
        LineChartView lineChartView = this.chart;
        if (lineChartView != null) {
            lineChartView.setAlpha(1.0f);
        }
    }

    public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bArr = new byte[1024];
        while (true) {
            try {
                int read = inputStream.read(bArr);
                if (read == -1) {
                    break;
                }
                byteArrayOutputStream.write(bArr, 0, read);
            } catch (IOException unused) {
            }
        }
        byteArrayOutputStream.close();
        inputStream.close();
        return byteArrayOutputStream.toString();
    }

    private void initializeSearchWords(String str) {
        Log.d(TAG, "Initialize Search words");
        wordDataWrapper worddatawrapper = new wordDataWrapper();
        try {
            worddatawrapper = (wordDataWrapper) new Gson().fromJson(readTextFile(getResources().openRawResource(2131689477)), wordDataWrapper.class);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "Got exception during search word load: " + e.toString());
            Toast.makeText(getApplicationContext(), xdrip.gs(2131756147), 1).show();
        }
        Log.d(TAG, "Loaded Words: " + worddatawrapper.entries.size());
        this.searchWords = worddatawrapper;
    }

    public void promptSpeechNoteInput(View view) {
        if (this.recognitionRunning) {
            return;
        }
        this.recognitionRunning = true;
        Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
        intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form");
        intent.putExtra("android.speech.extra.LANGUAGE", Locale.getDefault());
        intent.putExtra("android.speech.extra.PROMPT", getString(2131756403));
        try {
            startActivityForResult(intent, 1995);
        } catch (ActivityNotFoundException unused) {
            Toast.makeText(getApplicationContext(), getString(2131756409), 1).show();
        }
    }

    private void promptKeypadInput() {
        Log.d(TAG, "Showing pop-up");
        startActivity(new Intent(this, (Class<?>) PhoneKeypadInputActivity.class));
    }

    private void promptTextInput() {
        promptKeypadInput();
    }

    private void promptTextInput_old() {
        if (this.recognitionRunning) {
            return;
        }
        this.recognitionRunning = true;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(2131756925);
        final EditText editText = new EditText(this);
        editText.setInputType(1);
        builder.setView(editText);
        builder.setPositiveButton(2131755953, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.this.lambda$promptTextInput_old$27(editText, dialogInterface, i);
            }
        });
        builder.setNegativeButton(2131755280, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        final AlertDialog create = builder.create();
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public final void onFocusChange(View view, boolean z) {
                Home.lambda$promptTextInput_old$29(create, view, z);
            }
        });
        create.show();
        this.recognitionRunning = false;
    }

    public void lambda$promptTextInput_old$27(EditText editText, DialogInterface dialogInterface, int i) {
        this.voiceRecognitionText.setText(editText.getText().toString());
        this.voiceRecognitionText.setVisibility(0);
        last_speech_time = JoH.ts();
        naturalLanguageRecognition(editText.getText().toString());
    }

    public static void lambda$promptTextInput_old$29(AlertDialog alertDialog, View view, boolean z) {
        if (!z || alertDialog == null) {
            return;
        }
        alertDialog.getWindow().setSoftInputMode(5);
    }

    private synchronized void promptSpeechInput() {
        if (JoH.ratelimit("speech-input", 1)) {
            if (this.recognitionRunning) {
                return;
            }
            this.recognitionRunning = true;
            Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
            intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form");
            intent.putExtra("android.speech.extra.LANGUAGE", Locale.getDefault());
            intent.putExtra("android.speech.extra.PROMPT", getString(2131756404));
            try {
                startActivityForResult(intent, 1994);
            } catch (ActivityNotFoundException unused) {
                Toast.makeText(getApplicationContext(), 2131756409, 1).show();
            }
        }
    }

    private String classifyWord(String str) {
        if (str == null) {
            return null;
        }
        if (str.equals("watchkeypad")) {
            return "watchkeypad";
        }
        if (str.equals("uuid")) {
            return "uuid";
        }
        Iterator<wordData> it = this.searchWords.entries.iterator();
        while (it.hasNext()) {
            wordData next = it.next();
            if (next.matchWords.contains(str)) {
                Log.d(TAG, "Matched spoken word: " + str + " => " + next.lexicon);
                return next.lexicon;
            }
        }
        Log.d(TAG, "Could not match spoken word: " + str);
        return null;
    }

    private void naturalLanguageRecognition(String str) {
        if (this.searchWords == null) {
            Toast.makeText(getApplicationContext(), xdrip.gs(2131757052), 1).show();
            return;
        }
        String str2 = TAG;
        Log.d(str2, "Processing speech input allWords: " + str);
        this.thisuuid = "";
        int indexOf = str.indexOf(" uuid ");
        if (indexOf > 0) {
            this.thisuuid = indexOf > 0 ? str.substring(0, indexOf) : "";
            str = str.substring(indexOf + 6, str.length());
        }
        String lowerCase = str.trim().replaceAll(":", ".").replaceAll("(\\d)([a-zA-Z])", "$1 $2").replaceAll("([0-9]\\.[0-9])([0-9][0-9])", "$1 $2").replaceAll(new String(new byte[]{-30, Byte.MIN_VALUE, -113}, StandardCharsets.UTF_8), "").toLowerCase();
        Log.d(str2, "Processing speech input allWords second: " + lowerCase + " UUID: " + this.thisuuid);
        if (lowerCase.contentEquals("delete last treatment") || lowerCase.contentEquals("cancel last treatment") || lowerCase.contentEquals("erase last treatment")) {
            Treatments.delete_last(true);
            updateCurrentBgInfo("delete last treatment");
        } else if (lowerCase.contentEquals("delete all treatments") || lowerCase.contentEquals("delete all treatment")) {
            Treatments.delete_all(true);
            updateCurrentBgInfo("delete all treatment");
        } else if (lowerCase.contentEquals("delete all glucose data")) {
            deleteAllBG(null);
            LibreAlarmReceiver.clearSensorStats();
        } else if (lowerCase.contentEquals("test trend arrow")) {
            testGraphicalTrendArrow();
        } else {
            VoiceCommands.processVoiceCommand(lowerCase, this);
        }
        this.watchkeypad = false;
        this.watchkeypadset = false;
        this.glucoseset = false;
        this.thisInsulinSumNumber = BgReading.BESTOFFSET;
        this.thisinsulinnumber = new double[3];
        this.thisinsulinprofile = new Insulin[3];
        this.carbsset = false;
        this.timeset = false;
        this.thisnumber = -1.0d;
        this.thisword = "";
        for (int i = 0; i < this.maxInsulinProfiles; i++) {
            this.thisinsulinprofile[i] = null;
        }
        String[] split = lowerCase.split(" ");
        for (int i2 = 0; i2 < split.length; i2++) {
            try {
                this.thisnumber = Double.parseDouble(split[i2]);
                handleWordPair();
            } catch (NumberFormatException unused) {
                String classifyWord = classifyWord(split[i2]);
                if (classifyWord != null) {
                    this.thisword = classifyWord;
                } else {
                    this.thisword = split[i2].toLowerCase();
                }
                handleWordPair();
                if (this.thisword.equals("note")) {
                    String str3 = "";
                    for (int i3 = i2 + 1; i3 < split.length; i3++) {
                        if (str3.length() > 0) {
                            str3 = str3 + " ";
                        }
                        str3 = str3 + split[i3];
                    }
                    if (str3.length() > 0) {
                        Treatments.create_note(str3, JoH.tsl());
                        staticRefreshBGCharts();
                        return;
                    }
                } else {
                    continue;
                }
            }
        }
    }

    private void handleWordPair() {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.Home.handleWordPair():void");
    }

    public static void toaststatic(String str) {
        nexttoast = str;
        staticRefreshBGCharts();
    }

    public static void toaststaticnext(String str) {
        nexttoast = str;
        UserError.Log.uel(TAG, "Home toast message next: " + str);
    }

    public static void lambda$toast$30(String str) {
        Toast.makeText(mActivity, str, 1).show();
    }

    public void toast(final String str) {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    Home.lambda$toast$30(str);
                }
            });
            Log.d(TAG, "toast: " + str);
        } catch (Exception e) {
            Log.d(TAG, "Couldn't display toast: " + str + " / " + e.toString());
        }
    }

    @Override
    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i != 19312) {
            switch (i) {
                case 1994:
                    if (i2 == -1 && intent != null) {
                        ArrayList<String> stringArrayListExtra = intent.getStringArrayListExtra("android.speech.extra.RESULTS");
                        this.voiceRecognitionText.setText(stringArrayListExtra.get(0));
                        this.voiceRecognitionText.setVisibility(0);
                        last_speech_time = JoH.ts();
                        naturalLanguageRecognition(stringArrayListExtra.get(0));
                    }
                    this.recognitionRunning = false;
                    break;
                case 1995:
                    if (i2 == -1 && intent != null) {
                        ArrayList<String> stringArrayListExtra2 = intent.getStringArrayListExtra("android.speech.extra.RESULTS");
                        String trim = stringArrayListExtra2.get(0).trim();
                        Log.d(TAG, "Got treatment note: " + trim);
                        this.voiceRecognitionText.setText(stringArrayListExtra2.get(0));
                        this.voiceRecognitionText.setVisibility(0);
                        Treatments.create_note(trim, 0L);
                        AlertDialog alertDialog = this.dialog;
                        if (alertDialog != null) {
                            alertDialog.cancel();
                            this.dialog = null;
                        }
                        staticRefreshBGCharts();
                    }
                    this.recognitionRunning = false;
                    break;
                case 1996:
                    staticRefreshBGCharts();
                    break;
            }
        }
        if (NFCReaderX.useNFC()) {
            new NFCReaderX();
            NFCReaderX.tagFound(this, intent);
        }
    }

    class wordDataWrapper {
        public ArrayList<wordData> entries = new ArrayList<>();

        wordDataWrapper() {
        }
    }

    @Override
    public String getMenuName() {
        return getString(2131755665);
    }

    private boolean checkEula() {
        if (!Pref.getBoolean("warning_agreed_to", false)) {
            startActivity(new Intent(getApplicationContext(), (Class<?>) Agreement.class));
            finish();
            return false;
        }
        if (Pref.getBoolean("I_understand", false)) {
            return true;
        }
        startActivity(new Intent(getApplicationContext(), (Class<?>) LicenseAgreementActivity.class));
        finish();
        return false;
    }

    public static void staticRefreshBGCharts() {
        staticRefreshBGCharts(false);
    }

    public static void staticRefreshBGChartsOnIdle() {
        Inevitable.task("refresh-home-charts", 1000L, new Runnable() {
            @Override
            public final void run() {
                Home.staticRefreshBGCharts(false);
            }
        });
    }

    public static void staticRefreshBGCharts(boolean z) {
        reset_viewport = true;
        if (activityVisible || z) {
            Intent intent = new Intent("com.eveningoutpost.dexdrip.BgEstimateNoData");
            Activity activity = mActivity;
            if (activity != null) {
                activity.sendBroadcast(intent);
            }
        }
    }

    @TargetApi(21)
    private void handleFlairColors() {
        try {
            if (Pref.getBooleanDefaultFalse("use_flair_colors")) {
                getWindow().setNavigationBarColor(ColorCache.getCol(ColorCache.X.color_lower_flair_bar));
                getWindow().setStatusBarColor(ColorCache.getCol(ColorCache.X.color_upper_flair_bar));
            }
        } catch (Exception unused) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        xdrip.checkForcedEnglish(xdrip.getAppContext());
        handleFlairColors();
        checkEula();
        set_is_follower();
        statusIOB = "";
        statusBWP = "";
        refreshStatusLine();
        this.nanoStatus.setRunning(true);
        this.expiryStatus.setRunning(true);
        if (BgGraphBuilder.isXLargeTablet(getApplicationContext())) {
            this.currentBgValueText.setTextSize(100.0f);
            this.notificationText.setTextSize(40.0f);
            this.extraStatusLineText.setTextSize(40.0f);
        } else if (BgGraphBuilder.isLargeTablet(getApplicationContext())) {
            this.currentBgValueText.setTextSize(70.0f);
            this.notificationText.setTextSize(34.0f);
            this.extraStatusLineText.setTextSize(35.0f);
        }
        this._broadcastReceiver = new AnonymousClass6();
        this.newDataReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Home.this.lastDataTick = JoH.tsl();
                Home.this.updateCurrentBgInfo("new data");
                Home.this.updateHealthInfo("new_data");
            }
        };
        registerReceiver(this._broadcastReceiver, new IntentFilter("android.intent.action.TIME_TICK"));
        registerReceiver(this.newDataReceiver, new IntentFilter("com.eveningoutpost.dexdrip.BgEstimateNoData"));
        LocalBroadcastManager.getInstance(this).registerReceiver(this.statusReceiver, new IntentFilter("com.eveningoutpost.dexdrip.HOME_STATUS_ACTION"));
        if (invalidateMenu) {
            invalidateOptionsMenu();
            invalidateMenu = false;
        }
        activityVisible = true;
        updateCurrentBgInfo("generic on resume");
        updateHealthInfo("generic on resume");
        NFControl.initNFC(this, false);
        if (!get_follower()) {
            get_master();
        }
        checkWifiSleepPolicy();
        if (this.homeShelf.getDefaultFalse("source_wizard_auto") && Experience.gotData()) {
            this.homeShelf.set("source_wizard", false);
            this.homeShelf.set("source_wizard_auto", false);
        }
        HeyFamUpdateOptInDialog.heyFam(this);
        firstRunDialogs(this.checkedeula);
        Inevitable.task("home-resume-bg", 2000L, new Runnable() {
            @Override
            public final void run() {
                Home.lambda$onResume$32();
            }
        });
    }

    class AnonymousClass6 extends BroadcastReceiver {
        AnonymousClass6() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == null || !intent.getAction().equals("android.intent.action.TIME_TICK") || JoH.msSince(Home.this.lastDataTick) <= 30000) {
                return;
            }
            Inevitable.task("process-time-tick", 300L, new Runnable() {
                @Override
                public final void run() {
                    Home.AnonymousClass6.this.lambda$onReceive$1();
                }
            });
        }

        public void lambda$onReceive$1() {
            Home.this.runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    Home.AnonymousClass6.this.lambda$onReceive$0();
                }
            });
        }

        public void lambda$onReceive$0() {
            Home.this.updateCurrentBgInfo("time tick");
            Home.this.updateHealthInfo("time_tick");
        }
    }

    public static void lambda$onResume$32() {
        InPenEntry.startIfEnabled();
        EmergencyAssistActivity.checkPermissionRemoved();
        NightscoutUploader.launchDownloadRest();
        Pendiq.immortality();
    }

    private void checkWifiSleepPolicy() {
        if (Build.VERSION.SDK_INT >= 33 || JoH.getWifiSleepPolicyNever() || !JoH.ratelimit("policy-never", 3600) || Pref.getLong("wifi_warning_never", 0L) != 0 || JoH.isMobileDataOrEthernetConnected()) {
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(xdrip.gs(2131757045));
        builder.setMessage(xdrip.gs(2131757088));
        builder.setNeutralButton(xdrip.gs(2131755803), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.setPositiveButton(xdrip.gs(2131757075), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.this.lambda$checkWifiSleepPolicy$34(dialogInterface, i);
            }
        });
        builder.setNegativeButton(2131755913, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.lambda$checkWifiSleepPolicy$35(dialogInterface, i);
            }
        });
        builder.create().show();
    }

    public void lambda$checkWifiSleepPolicy$34(DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        toast(xdrip.gs(2131756173));
        try {
            startActivity(new Intent("android.settings.WIFI_IP_SETTINGS"));
        } catch (ActivityNotFoundException unused) {
            JoH.static_toast_long(xdrip.gs(2131755964));
        }
    }

    public static void lambda$checkWifiSleepPolicy$35(DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        Pref.setLong("wifi_warning_never", (long) JoH.ts());
    }

    protected static class InterceptingGestureHandler extends GestureDetector {
        final Home context;
        final GestureDetector originalDetector;

        public InterceptingGestureHandler(Home home, GestureDetector gestureDetector) {
            super(home, new GestureDetector.SimpleOnGestureListener() {
            });
            this.originalDetector = gestureDetector;
            this.context = home;
        }

        @Override
        public boolean onTouchEvent(MotionEvent motionEvent) {
            if (motionEvent.getAction() == 2) {
                if (JoH.quietratelimit("viewport-intercept", 5)) {
                    UserError.Log.d("VIEWPORT", "Intercept gesture move event " + motionEvent);
                }
                this.context.lastViewPortPan = JoH.tsl();
            }
            return this.originalDetector.onTouchEvent(motionEvent);
        }
    }

    private void setupCharts(String str) {
        LineChartView lineChartView;
        String str2 = TAG;
        UserError.Log.d(str2, "VIEWPORT setupCharts source: " + str);
        this.bgGraphBuilder = new BgGraphBuilder(this);
        this.updateStuff = false;
        this.chart = findViewById(2131296489);
        if (BgGraphBuilder.isXLargeTablet(getApplicationContext())) {
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) this.chart.getLayoutParams();
            marginLayoutParams.topMargin = 130;
            this.chart.setLayoutParams(marginLayoutParams);
        }
        this.chart.setBackgroundColor(ColorCache.getCol(ColorCache.X.color_home_chart_background));
        this.chart.setZoomType(ZoomType.HORIZONTAL);
        this.chart.setMaxZoom(50.0d);
        try {
            Field declaredField = ChartTouchHandler.class.getDeclaredField("gestureDetector");
            declaredField.setAccessible(true);
            ChartTouchHandler touchHandler = this.chart.getTouchHandler();
            ChartTouchHandler touchHandler2 = this.previewChart.getTouchHandler();
            GestureDetector gestureDetector = (GestureDetector) declaredField.get(touchHandler);
            GestureDetector gestureDetector2 = (GestureDetector) declaredField.get(touchHandler2);
            if (!(gestureDetector instanceof InterceptingGestureHandler)) {
                declaredField.set(touchHandler, new InterceptingGestureHandler(this, gestureDetector));
            } else {
                UserError.Log.d(str2, "Already intercepting viewport");
            }
            if (!(gestureDetector2 instanceof InterceptingGestureHandler)) {
                declaredField.set(touchHandler2, new InterceptingGestureHandler(this, gestureDetector2));
            }
        } catch (ClassCastException | IllegalAccessException | NoSuchFieldException | NullPointerException e) {
            UserError.Log.d(TAG, "Exception injecting touch handler: " + e);
        }
        this.chart.getChartData().setAxisXTop((Axis) null);
        this.previewChart = findViewById(2131296490);
        this.chart.setLineChartData(this.bgGraphBuilder.lineData());
        this.chart.setOnValueTouchListener(this.bgGraphBuilder.getOnValueSelectTooltipListener(mActivity));
        this.previewChart.setBackgroundColor(ColorCache.getCol(ColorCache.X.color_home_chart_background));
        this.previewChart.setZoomType(ZoomType.HORIZONTAL);
        this.previewChart.setLineChartData(this.bgGraphBuilder.previewLineData(this.chart.getLineChartData()));
        this.previewChart.setViewportCalculationEnabled(true);
        this.previewChart.setViewportChangeListener(new PreviewChartViewportListener());
        this.chart.setViewportCalculationEnabled(true);
        this.chart.setViewportChangeListener(new MainChartViewPortListener());
        this.updateStuff = true;
        if (this.small_height) {
            this.previewChart.setVisibility(8);
            Viewport viewport = new Viewport(this.chart.getMaximumViewport());
            float width = ((float) viewport.width()) / 4.0f;
            Viewport viewport2 = this.holdViewport;
            double d = viewport.right;
            viewport2.left = d - width;
            viewport2.right = d + (viewport.width() / 24.0d);
            Viewport viewport3 = this.holdViewport;
            viewport3.top = viewport.top;
            viewport3.bottom = viewport.bottom;
            this.chart.setCurrentViewport(viewport3);
            this.previewChart.setCurrentViewport(this.holdViewport);
            UserError.Log.e(TAG, "SMALL HEIGHT VIEWPORT WARNING");
        } else {
            if (this.homeShelf.get("time_buttons") || this.homeShelf.get("time_locked_always")) {
                long j = PersistentStore.getLong("home-locked-hours");
                if (j > 0) {
                    hours = j;
                } else {
                    hours = 2.5f;
                }
                setHoursViewPort(str);
            } else {
                hours = 2.5f;
                setHoursViewPort(str);
            }
            this.previewChart.setVisibility(this.homeShelf.get("chart_preview") ? 0 : 8);
        }
        if ((this.insulinsumset || this.glucoseset || this.carbsset || this.timeset) && (lineChartView = this.chart) != null) {
            lineChartView.setAlpha(0.1f);
        }
    }

    @Override
    public void onPause() {
        activityVisible = false;
        super.onPause();
        NFControl.initNFC(this, true);
        this.nanoStatus.setRunning(false);
        this.expiryStatus.setRunning(false);
        BroadcastReceiver broadcastReceiver = this._broadcastReceiver;
        if (broadcastReceiver != null) {
            try {
                unregisterReceiver(broadcastReceiver);
            } catch (IllegalArgumentException e) {
                UserError.Log.e(TAG, "_broadcast_receiver not registered", e);
            }
        }
        BroadcastReceiver broadcastReceiver2 = this.newDataReceiver;
        if (broadcastReceiver2 != null) {
            try {
                unregisterReceiver(broadcastReceiver2);
            } catch (IllegalArgumentException e2) {
                UserError.Log.e(TAG, "newDataReceiver not registered", e2);
            }
        }
        try {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(this.statusReceiver);
        } catch (Exception e3) {
            Log.e(TAG, "Exception unregistering broadcast receiver: " + e3);
        }
    }

    private static void set_is_follower() {
        is_follower = PreferenceManager.getDefaultSharedPreferences(xdrip.getAppContext()).getString("dex_collection_method", "").equals("Follower");
        is_follower_set = true;
    }

    public static boolean get_follower() {
        if (!is_follower_set) {
            set_is_follower();
        }
        return is_follower;
    }

    private static void setHasLibreblock() {
        has_libreblock = LibreBlock.getLatestForTrend() != null;
        has_libreblock_set = true;
    }

    public static boolean hasLibreblock() {
        if (!has_libreblock_set) {
            setHasLibreblock();
        }
        return has_libreblock;
    }

    public static boolean get_is_libre_whole_house_collector() {
        return Pref.getBooleanDefaultFalse("libre_whole_house_collector");
    }

    public static boolean get_engineering_mode() {
        return Pref.getBooleanDefaultFalse("engineering_mode");
    }

    public static boolean get_master() {
        return !get_follower() && Pref.getBooleanDefaultFalse("plus_follow_master");
    }

    public static boolean get_master_or_follower() {
        return get_follower() || get_master();
    }

    public static boolean get_show_wear_treatments() {
        return Pref.getBooleanDefaultFalse("wear_sync") && Pref.getBooleanDefaultFalse("show_wear_treatments");
    }

    public static boolean follower_or_accept_follower() {
        return get_follower() || Pref.getBoolean("plus_accept_follower_actions", true);
    }

    public static boolean get_forced_wear() {
        return Pref.getBooleanDefaultFalse("wear_sync") && Pref.getBooleanDefaultFalse("enable_wearG5") && Pref.getBooleanDefaultFalse("force_wearG5");
    }

    public static boolean get_enable_wear() {
        return Pref.getBooleanDefaultFalse("wear_sync") && Pref.getBooleanDefaultFalse("enable_wearG5");
    }

    public static void startWatchUpdaterService(Context context, String str, String str2) {
        if (Pref.getBoolean("wear_sync", false)) {
            Log.d(str2, "start WatchUpdaterService with " + str);
            context.startService(new Intent(context, (Class<?>) WatchUpdaterService.class).setAction(str));
        }
    }

    public static void startWatchUpdaterService(Context context, String str, String str2, String str3, String str4) {
        if (Pref.getBoolean("wear_sync", false)) {
            Log.d(str2, "start WatchUpdaterService with " + str);
            context.startService(new Intent(context, (Class<?>) WatchUpdaterService.class).setAction(str).putExtra(str3, str4));
        }
    }

    public static void startWatchUpdaterService(Context context, String str, String str2, String str3, boolean z) {
        if (Pref.getBoolean("wear_sync", false)) {
            Log.d(str2, "start WatchUpdaterService with " + str);
            context.startService(new Intent(context, (Class<?>) WatchUpdaterService.class).setAction(str).putExtra(str3, z));
        }
    }

    public static boolean get_holo() {
        return is_holo;
    }

    public void toggleStepsVisibility(View view) {
        Pref.setBoolean("show_pebble_movement_line", true ^ Pref.getBoolean("show_pebble_movement_line", true));
        staticRefreshBGCharts();
    }

    public void sourceWizardButtonClick(View view) {
        SourceWizard.start(this, true);
    }

    private long whichTimeLocked() {
        return PersistentStore.getLong("home-locked-hours");
    }

    private void setHourLocked(float f) {
        PersistentStore.setLong("home-locked-hours", (long) f);
    }

    public boolean isHourLocked(long j) {
        return whichTimeLocked() == j;
    }

    public boolean isHourLocked(long j, int i) {
        return isHourLocked(j);
    }

    private void setHoursViewPort(java.lang.String r9) {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.Home.setHoursViewPort(java.lang.String):void");
    }

    public void timeButtonClick(View view) {
        hours = getButtonHours(view);
        setHoursViewPort("timeButtonClick");
    }

    private long getButtonHours(View view) {
        switch (view.getId()) {
            case 2131296651:
                return 12L;
            case 2131296652:
                return 24L;
            case 2131296653:
            default:
                return 3L;
            case 2131296654:
                return 6L;
        }
    }

    public boolean timeButtonLongClick(View view) {
        long buttonHours = getButtonHours(view);
        if (isHourLocked(buttonHours)) {
            setHourLocked(0.0f);
            hours = 2.5f;
        } else {
            float f = buttonHours;
            hours = f;
            setHourLocked(f);
            setHoursViewPort("timeButtonLongClick");
        }
        this.ui.bump();
        return false;
    }

    public void updateHealthInfo(String str) {
        StepCounter last = StepCounter.last();
        boolean z = Pref.getBoolean("use_pebble_health", true);
        if (z && last != null) {
            this.stepsButton.setText(Integer.toString(StepCounter.getDailyTotal()));
            this.stepsButton.setVisibility(0);
            this.stepsButton.setAlpha(Pref.getBoolean("show_pebble_movement_line", true) ? 1.0f : 0.3f);
        } else {
            this.stepsButton.setVisibility(4);
        }
        HeartRate last2 = HeartRate.last();
        if (z && last2 != null) {
            this.bpmButton.setText(Integer.toString(last2.bpm));
            this.bpmButton.setVisibility(0);
            this.bpmButton.setAlpha(Pref.getBoolean("show_pebble_movement_line", true) ? 1.0f : 0.3f);
            return;
        }
        this.bpmButton.setVisibility(4);
    }

    public void updateCurrentBgInfo(String str) {
        int i;
        String str2 = TAG;
        Log.d(str2, "updateCurrentBgInfo from: " + str);
        if (!activityVisible) {
            Log.d(str2, "Display not visible - not updating chart");
            return;
        }
        if (reset_viewport) {
            reset_viewport = false;
        }
        setupCharts(str);
        initializeGraphicTrendArrow();
        TextView textView = (TextView) findViewById(2131296816);
        TextView textView2 = (TextView) findViewById(2131296732);
        if (BgGraphBuilder.isXLargeTablet(getApplicationContext())) {
            textView.setTextSize(40.0f);
            textView2.setTextSize(30.0f);
        }
        textView.setText("");
        textView.setTextColor(-65536);
        UndoRedo.purgeQueues();
        if (UndoRedo.undoListHasItems()) {
            this.btnUndo.setVisibility(0);
            showcasemenu(4);
        } else {
            this.btnUndo.setVisibility(4);
        }
        if (UndoRedo.redoListHasItems()) {
            this.btnRedo.setVisibility(0);
            showcasemenu(5);
        } else {
            this.btnRedo.setVisibility(4);
        }
        DexCollectionType dexCollectionType = DexCollectionType.getDexCollectionType();
        boolean isBTWixelOrLimiTTer = CollectionServiceStarter.isBTWixelOrLimiTTer(getApplicationContext());
        boolean isDexBridgeOrWifiandDexBridge = CollectionServiceStarter.isDexBridgeOrWifiandDexBridge();
        boolean isWifiandBTWixel = CollectionServiceStarter.isWifiandBTWixel(getApplicationContext());
        boolean isWifiandBTLibre = CollectionServiceStarter.isWifiandBTLibre(getApplicationContext());
        this.isBTShare = CollectionServiceStarter.isBTShare(getApplicationContext());
        this.isG5Share = CollectionServiceStarter.isBTG5(getApplicationContext());
        boolean isWifiWixel = CollectionServiceStarter.isWifiWixel(getApplicationContext());
        boolean isWifiLibre = CollectionServiceStarter.isWifiLibre(getApplicationContext());
        this.alreadyDisplayedBgInfoCommon = false;
        if (this.isBTShare) {
            updateCurrentBgInfoForBtShare(textView);
        }
        if (this.isG5Share) {
            updateCurrentBgInfoCommon(dexCollectionType, textView);
        }
        if (isBTWixelOrLimiTTer || isDexBridgeOrWifiandDexBridge || isWifiandBTWixel || isWifiandBTLibre) {
            updateCurrentBgInfoForBtBasedWixel(dexCollectionType, textView);
        }
        if (isWifiWixel || isWifiandBTWixel || isWifiandBTLibre || isWifiLibre || dexCollectionType.equals(DexCollectionType.Mock)) {
            updateCurrentBgInfoForWifiWixel(dexCollectionType, textView);
        } else if (is_follower || dexCollectionType.isPassive()) {
            displayCurrentInfo();
            Inevitable.task("home-notifications-start", 5000L, new Runnable() {
                @Override
                public final void run() {
                    Notifications.start();
                }
            });
        } else if (!this.alreadyDisplayedBgInfoCommon && (DexCollectionType.getDexCollectionType() == DexCollectionType.LibreAlarm || dexCollectionType == DexCollectionType.Medtrum)) {
            updateCurrentBgInfoCommon(dexCollectionType, textView);
        }
        if (dexCollectionType.equals(DexCollectionType.Disabled)) {
            textView.append(getString(2131755026));
            if (!Experience.gotData()) {
                JoH.runOnUiThreadDelayed(new Runnable() {
                    @Override
                    public final void run() {
                        Home.this.lambda$updateCurrentBgInfo$36(this);
                    }
                }, 500L);
            }
        } else if (dexCollectionType.equals(DexCollectionType.Mock)) {
            textView.append("\n USING FAKE DATA SOURCE !!!");
            if (MockDataSource.divisor_scale == 1500000.0d) {
                textView.append(" F");
            }
            if (MockDataSource.amplify_cnst == 330000.0d) {
                textView.append(" Amp");
            }
        }
        if (Pref.getLong("alerts_disabled_until", 0L) > new Date().getTime()) {
            textView.append("\n " + getString(2131755120));
        } else if (Pref.getLong("low_alerts_disabled_until", 0L) > new Date().getTime() && Pref.getLong("high_alerts_disabled_until", 0L) > new Date().getTime()) {
            textView.append("\n " + getString(2131755782));
        } else if (Pref.getLong("low_alerts_disabled_until", 0L) > new Date().getTime()) {
            textView.append("\n " + getString(2131755780));
        } else if (Pref.getLong("high_alerts_disabled_until", 0L) > new Date().getTime()) {
            textView.append("\n " + getString(2131755659));
        }
        NavigationDrawerFragment navigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(2131296801);
        if (BgGraphBuilder.last_noise > BgReading.BESTOFFSET && Pref.getBoolean("show_noise_workings", false)) {
            textView.append("\nSensor Noise: " + JoH.qs(BgGraphBuilder.last_noise, 1));
            if (BgGraphBuilder.best_bg_estimate > BgReading.BESTOFFSET && BgGraphBuilder.last_bg_estimate > BgReading.BESTOFFSET) {
                double d = BgGraphBuilder.best_bg_estimate - BgGraphBuilder.last_bg_estimate;
                try {
                    textView.append("\nBG Original: " + this.bgGraphBuilder.unitized_string(BgGraphBuilder.original_value) + " Δ " + this.bgGraphBuilder.unitizedDeltaString(false, true, true) + " " + BgReading.lastNoSenssor().slopeArrow());
                    textView.append("\nBG Estimate: " + this.bgGraphBuilder.unitized_string(BgGraphBuilder.best_bg_estimate) + " Δ " + this.bgGraphBuilder.unitizedDeltaStringRaw(false, true, d) + " " + BgReading.slopeToArrowSymbol(d / 5.0d));
                } catch (NullPointerException unused) {
                }
            }
        }
        textView2.setText("");
        textView2.setVisibility(4);
        if (BgGraphBuilder.low_occurs_at > BgReading.BESTOFFSET) {
            double d2 = JoH.tolerantParseDouble(Pref.getString("low_predict_alarm_level", "50"), 50.0d);
            double ts = JoH.ts();
            double d3 = (BgGraphBuilder.low_occurs_at - ts) / 60000.0d;
            if (d3 > 1.0d) {
                textView2.append(getString(2131755790) + "\n" + getString(2131755681) + ": " + ((int) d3) + getString(2131756395));
                if (d3 < d2) {
                    textView2.setTextColor(-65536);
                } else {
                    double d4 = BgGraphBuilder.previous_low_occurs_at;
                    double d5 = (d4 - ts) / 60000.0d;
                    if (d4 > BgReading.BESTOFFSET && d5 + 5.0d < d3) {
                        textView2.setTextColor(-16711936);
                    } else {
                        textView2.setTextColor(-256);
                    }
                }
                textView2.setVisibility(0);
            }
            BgGraphBuilder.previous_low_occurs_at = BgGraphBuilder.low_occurs_at;
        }
        if (navigationDrawerFragment == null) {
            Log.e("Runtime", "navigationdrawerfragment is null");
        }
        try {
            navigationDrawerFragment.setUp(2131296801, (DrawerLayout) findViewById(2131296561), getString(2131755665), this);
        } catch (Exception e) {
            Log.e("Runtime", "Exception with navigrationdrawerfragment: " + e.toString());
        }
        String str3 = nexttoast;
        if (str3 != null) {
            toast(str3);
            nexttoast = null;
        }
        if (last_speech_time <= BgReading.BESTOFFSET || JoH.ts() - last_speech_time <= 20000.0d) {
            i = 4;
        } else {
            i = 4;
            this.voiceRecognitionText.setVisibility(4);
            last_speech_time = BgReading.BESTOFFSET;
        }
        if (ActivityRecognizedService.is_in_vehicle_mode()) {
            this.btnVehicleMode.setVisibility(0);
        } else {
            this.btnVehicleMode.setVisibility(i);
        }
    }

    public void lambda$updateCurrentBgInfo$36(Activity activity) {
        AlertDialog alertDialog = this.dialog;
        if ((alertDialog == null || !alertDialog.isShowing()) && JoH.ratelimit("start_source_wizard", 30)) {
            SourceWizard.start(activity, false);
        }
    }

    private void updateCurrentBgInfoForWifiWixel(DexCollectionType dexCollectionType, TextView textView) {
        if (!WixelReader.IsConfigured()) {
            textView.setText(2131755579);
        } else {
            updateCurrentBgInfoCommon(dexCollectionType, textView);
        }
    }

    private void updateCurrentBgInfoForBtBasedWixel(DexCollectionType dexCollectionType, TextView textView) {
        if (ActiveBluetoothDevice.first() == null) {
            textView.setText(2131755582);
        } else {
            updateCurrentBgInfoCommon(dexCollectionType, textView);
        }
    }

    private void updateCurrentBgInfoCommon(DexCollectionType dexCollectionType, TextView textView) {
        if (this.alreadyDisplayedBgInfoCommon) {
            return;
        }
        this.alreadyDisplayedBgInfoCommon = true;
        if (get_is_libre_whole_house_collector()) {
            Long valueOf = Long.valueOf(PersistentStore.getLong("libre-reading-timestamp"));
            if (valueOf.longValue() == 0) {
                textView.setText(2131755683);
                return;
            }
            int tsl = ((int) (JoH.tsl() - valueOf.longValue())) / UsbId.SILABS_CP2102;
            String string = getString(2131755830);
            textView.setText(2131755682);
            textView.append(MessageFormat.format(string, Integer.valueOf(tsl)));
            return;
        }
        boolean isActive = Sensor.isActive();
        if (!isActive && Ob1G5CollectionService.isG5SensorStarted() && !Sensor.stoppedRecently()) {
            JoH.static_toast_long(getString(2131755178));
            Sensor.create(JoH.tsl() - 10800000);
            isActive = Sensor.isActive();
        }
        if (!isActive) {
            boolean z = DexCollectionType.getDexCollectionType() == DexCollectionType.DexcomG5 && Pref.getBooleanDefaultFalse("ob1_g5_use_transmitter_alg") && Pref.getBooleanDefaultFalse("using_g6") && (DexTimeKeeper.getTransmitterAgeInDays(Ob1G5CollectionService.getTransmitterID()) == -1 || !DexSyncKeeper.isReady(Ob1G5CollectionService.getTransmitterID()));
            if (z || Ob1G5StateMachine.shortTxId()) {
                textView.setText(2131757015);
            } else {
                textView.setText(2131755946);
            }
            AlertDialog alertDialog = this.dialog;
            if (alertDialog == null || !alertDialog.isShowing()) {
                if (!Experience.gotData() && Experience.backupAvailable() && JoH.ratelimit("restore-backup-prompt", 10)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle(xdrip.gs(2131756208));
                    builder.setMessage(xdrip.gs(2131755477) + Pref.getString("last-saved-database-zip", "ERROR").replaceFirst("^.*/", ""));
                    builder.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
                        @Override
                        public final void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                    builder.setPositiveButton(xdrip.gs(2131756207), new DialogInterface.OnClickListener() {
                        @Override
                        public final void onClick(DialogInterface dialogInterface, int i) {
                            Home.this.lambda$updateCurrentBgInfoCommon$38(this, dialogInterface, i);
                        }
                    });
                    AlertDialog create = builder.create();
                    this.dialog = create;
                    create.show();
                    return;
                }
                if (Experience.gotData() || QuickSettingsDialogs.isDialogShowing() || z || !JoH.ratelimit("start-sensor_prompt", 20)) {
                    return;
                }
                AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
                builder2.setTitle(getString(2131756417) + "?");
                builder2.setMessage(String.format(xdrip.gs(2131756418), DexCollectionType.getBestCollectorHardwareName()));
                builder2.setNegativeButton(xdrip.gs(2131755311), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.this.lambda$updateCurrentBgInfoCommon$39(this, dialogInterface, i);
                    }
                });
                builder2.setPositiveButton(2131756417, new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.this.lambda$updateCurrentBgInfoCommon$40(this, dialogInterface, i);
                    }
                });
                AlertDialog create2 = builder2.create();
                this.dialog = create2;
                create2.show();
                return;
            }
            return;
        }
        if (!BgReading.doWeHaveRecentUsableData()) {
            long j = Sensor.currentSensor().started_at;
            long start = SensorDays.get().getStart();
            if (start > 0 && JoH.msSince(start) < 10800000) {
                j = Math.min(start, j);
            }
            long warmupMs = SensorDays.get().getWarmupMs();
            if (j + warmupMs > JoH.tsl()) {
                textView.setText(getString(2131756026) + JoH.qs((r7 - r5) / 60000.0d, 0) + getString(2131755831));
                showUncalibratedSlope();
                return;
            }
        }
        if (DexCollectionType.isLibreOOPNonCalibratebleAlgorithm(dexCollectionType)) {
            displayCurrentInfo();
            return;
        }
        if (Ob1G5CollectionService.isG5ActiveButUnknownState() && Calibration.latestValid(2).size() < 2) {
            String gs = xdrip.gs(2131756422);
            Object[] objArr = new Object[1];
            objArr[0] = Ob1G5StateMachine.usingG6() ? Ob1G5StateMachine.shortTxId() ? "G7" : "G6" : "G5";
            textView.setText(String.format(gs, objArr));
            showUncalibratedSlope();
            return;
        }
        if (Ob1G5CollectionService.isG5WarmingUp() || Ob1G5CollectionService.isPendingStart()) {
            textView.setText(2131756288);
            showUncalibratedSlope();
            return;
        }
        int size = BgReading.latest(3).size();
        if (size > 2 || (Ob1G5CollectionService.onlyUsingNativeMode() && BgReading.latest(1).size() > 0)) {
            List<Calibration> latestValid = Calibration.latestValid(2);
            if ((latestValid != null && latestValid.size() > 1) || Ob1G5CollectionService.onlyUsingNativeMode()) {
                if (latestValid.size() > 1 && latestValid.get(0).possible_bad != null && latestValid.get(0).possible_bad.booleanValue() && latestValid.get(1).possible_bad != null && !latestValid.get(1).possible_bad.booleanValue()) {
                    textView.setText(2131756031);
                }
                displayCurrentInfo();
                if (this.screen_forced_on) {
                    dontKeepScreenOn();
                    return;
                }
                return;
            }
            if (BgReading.isDataSuitableForDoubleCalibration()) {
                textView.setText(2131756015);
                showUncalibratedSlope();
                Log.d(TAG, "Asking for calibration A: Uncalculated BG readings: " + BgReading.latest(2).size() + " / Calibrations size: " + latestValid.size());
                promptForCalibration();
                dontKeepScreenOn();
                return;
            }
            textView.setText(2131756942);
            if (Ob1G5CollectionService.isProvidingNativeGlucoseData()) {
                displayCurrentInfo();
                if (this.screen_forced_on) {
                    dontKeepScreenOn();
                    return;
                }
                return;
            }
            return;
        }
        String str = TAG;
        UserError.Log.d(str, "NOT ENOUGH CALCULATED READINGS: " + size);
        if (!BgReading.isDataSuitableForDoubleCalibration() && (!Ob1G5CollectionService.usingNativeMode() || Ob1G5CollectionService.fallbackToXdripAlgorithm())) {
            textView.setText(2131756024);
            showInitialStatusHelper();
            return;
        }
        List<Calibration> latest = Calibration.latest(2);
        if (latest.size() < 2) {
            if (BgReading.isDataSuitableForDoubleCalibration() || Ob1G5CollectionService.isG5WantingInitialCalibration()) {
                textView.setText(2131756015);
                showUncalibratedSlope();
                Log.d(str, "Asking for calibration B: Uncalculated BG readings: " + BgReading.latestUnCalculated(2).size() + " / Calibrations size: " + latest.size() + " quality: " + BgReading.isDataSuitableForDoubleCalibration());
                if (!Ob1G5CollectionService.isPendingCalibration()) {
                    promptForCalibration();
                } else {
                    textView.setText(2131756902);
                }
            } else if (!Ob1G5CollectionService.isG5SensorStarted()) {
                textView.setText(2131756289);
            } else {
                textView.setText(2131755924);
            }
            dontKeepScreenOn();
        }
    }

    public void lambda$updateCurrentBgInfoCommon$38(Context context, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        startActivity(new Intent(context, (Class<?>) ImportDatabaseActivity.class).putExtra("importit", Pref.getString("last-saved-database-zip", "")).setFlags(268435456));
    }

    public void lambda$updateCurrentBgInfoCommon$39(Context context, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        startActivity(new Intent(context, (Class<?>) Preferences.class).setFlags(268435456));
    }

    public void lambda$updateCurrentBgInfoCommon$40(Context context, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        startActivity(new Intent(context, (Class<?>) StartNewSensor.class).setFlags(268435456));
    }

    private synchronized void showInitialStatusHelper() {
        if (checkBatteryOptimization()) {
            this.initialDataQuality = ProcessInitialDataQuality.getInitialDataQuality();
            AlertDialog alertDialog = this.helper_dialog;
            if (alertDialog != null && alertDialog.isShowing()) {
                this.helper_dialog.dismiss();
            }
            AlertDialog alertDialog2 = this.status_helper_dialog;
            if (alertDialog2 != null && alertDialog2.isShowing()) {
                PopupInitialStatusHelperBinding popupInitialStatusHelperBinding = this.initial_status_binding;
                if (popupInitialStatusHelperBinding != null) {
                    popupInitialStatusHelperBinding.setIdq(this.initialDataQuality);
                }
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(2131755343);
            PopupInitialStatusHelperBinding inflate = PopupInitialStatusHelperBinding.inflate(getLayoutInflater());
            this.initial_status_binding = inflate;
            inflate.setIdq(this.initialDataQuality);
            if (this.microStatus == null) {
                this.microStatus = new MicroStatusImpl();
            }
            this.initial_status_binding.setMs(this.microStatus);
            this.initial_status_binding.setPrefs(new PrefsViewImpl());
            builder.setView(this.initial_status_binding.getRoot());
            AlertDialog create = builder.create();
            this.status_helper_dialog = create;
            create.setCanceledOnTouchOutside(true);
            try {
                this.status_helper_dialog.show();
            } catch (Exception e) {
                UserError.Log.e(TAG, "Could not display calibration prompt helper: " + e);
            }
            keepScreenOn();
        }
    }

    private synchronized void promptForCalibration() {
        AlertDialog alertDialog = this.status_helper_dialog;
        if (alertDialog != null && alertDialog.isShowing()) {
            this.status_helper_dialog.dismiss();
        }
        AlertDialog alertDialog2 = this.helper_dialog;
        if (alertDialog2 == null || !alertDialog2.isShowing()) {
            if (this.btnApprove.getVisibility() == 0) {
                return;
            }
            if (JoH.ratelimit("calibrate-sensor_prompt", 10)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(xdrip.gs(2131755263));
                builder.setMessage(xdrip.gs(2131757022));
                builder.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.this.lambda$promptForCalibration$41(dialogInterface, i);
                    }
                });
                builder.setPositiveButton(xdrip.gs(2131755258), new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface, int i) {
                        Home.this.lambda$promptForCalibration$42(this, dialogInterface, i);
                    }
                });
                AlertDialog create = builder.create();
                this.helper_dialog = create;
                try {
                    create.show();
                } catch (Exception e) {
                    UserError.Log.e(TAG, "Could not display calibration prompt helper: " + e);
                }
                if (Pref.getBooleanDefaultFalse("play_sound_for_initial_calibration") && JoH.ratelimit("play_calibration_sound", 280)) {
                    JoH.playSoundUri(JoH.getResourceURI(2131689968));
                }
                keepScreenOn();
            }
        }
    }

    public void lambda$promptForCalibration$41(DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        this.helper_dialog = null;
    }

    public void lambda$promptForCalibration$42(Context context, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        this.helper_dialog = null;
        startActivity(new Intent(context, (Class<?>) DoubleCalibrationActivity.class).setFlags(268435456));
    }

    private void showUncalibratedSlope() {
        this.currentBgValueText.setText(BgReading.getSlopeArrowSymbolBeforeCalibration());
        this.currentBgValueText.setTextColor(ColorCache.getCol(ColorCache.X.color_predictive));
    }

    private void updateCurrentBgInfoForBtShare(TextView textView) {
        String upperCase = Pref.getString("share_key", "SM00000000").toUpperCase();
        if (upperCase.compareTo("SM00000000") == 0 || upperCase.length() == 0) {
            textView.setText(2131756020);
            return;
        }
        if (upperCase.length() < 10) {
            textView.setText(2131755484);
            return;
        }
        if (ActiveBluetoothDevice.first() == null) {
            textView.setText(2131755945);
        } else if (!Sensor.isActive()) {
            textView.setText(2131755944);
        } else {
            displayCurrentInfo();
        }
    }

    private void displayCurrentInfo() {
        new DecimalFormat("#").setMaximumFractionDigits(0);
        boolean isDexBridgeOrWifiandDexBridge = CollectionServiceStarter.isDexBridgeOrWifiandDexBridge();
        boolean isLimitter = CollectionServiceStarter.isLimitter();
        if (DexCollectionType.hasBattery()) {
            int i = Pref.getInt("bridge_battery", 0);
            if (i < 1) {
                this.dexbridgeBattery.setVisibility(4);
            } else if (isDexBridgeOrWifiandDexBridge) {
                this.dexbridgeBattery.setText(getString(2131757054) + ": " + i + "%");
            } else if (isLimitter) {
                String bestLimitterHardwareName = DexCollectionService.getBestLimitterHardwareName();
                if (bestLimitterHardwareName.equals("LimiTTer")) {
                    this.dexbridgeBattery.setText(getString(2131755758) + ": " + i + "%");
                } else if (bestLimitterHardwareName.equals("BlueReader")) {
                    if (Pref.getBooleanDefaultFalse("blueReader_restdays_on_home")) {
                        this.dexbridgeBattery.setText(bestLimitterHardwareName + " " + getString(2131755205) + ": " + i + "% (" + PersistentStore.getString("bridge_battery_days") + " " + getString(2131755405) + ")");
                    } else {
                        this.dexbridgeBattery.setText(bestLimitterHardwareName + " " + getString(2131755205) + ": " + i + "%");
                    }
                } else {
                    this.dexbridgeBattery.setText(bestLimitterHardwareName + " " + getString(2131755205) + ": " + i + "%");
                }
            } else {
                TextView textView = this.dexbridgeBattery;
                StringBuilder sb = new StringBuilder();
                sb.append(getString(2131755244));
                sb.append(": ");
                sb.append(i);
                sb.append(i < 200 ? "%" : "mV");
                textView.setText(sb.toString());
            }
            if (i < 50) {
                this.dexbridgeBattery.setTextColor(-256);
            }
            if (i < 25) {
                this.dexbridgeBattery.setTextColor(-65536);
            } else {
                this.dexbridgeBattery.setTextColor(-16711936);
            }
            this.dexbridgeBattery.setVisibility(0);
        } else {
            this.dexbridgeBattery.setVisibility(4);
        }
        if (DexCollectionType.hasWifi()) {
            int i2 = Pref.getInt("parakeet_battery", 0);
            if (i2 > 0) {
                if (i2 < 50) {
                    this.parakeetBattery.setText(getString(2131755984) + ": " + i2 + "%");
                    if (i2 < 40) {
                        this.parakeetBattery.setTextColor(-65536);
                    } else {
                        this.parakeetBattery.setTextColor(-256);
                    }
                    this.parakeetBattery.setVisibility(0);
                } else {
                    this.parakeetBattery.setVisibility(4);
                }
            }
        } else {
            this.parakeetBattery.setVisibility(4);
        }
        if (!Pref.getBoolean("display_bridge_battery", true)) {
            this.dexbridgeBattery.setVisibility(4);
            this.parakeetBattery.setVisibility(4);
        }
        int i3 = Pref.getInt("nfc_sensor_age", 0);
        if (i3 > 0 && (DexCollectionType.hasLibre() || hasLibreblock())) {
            String str = Pref.getBooleanDefaultFalse("nfc_age_problem") ? " ⚠⚠⚠" : "";
            if (Pref.getBoolean("nfc_show_age", true)) {
                this.sensorAge.setText(getResources().getQuantityString(2131623956, i3 / 1440, JoH.qs(i3 / 1440.0d, 1)) + str);
            } else {
                try {
                    double d = JoH.tolerantParseDouble(Pref.getString("nfc_expiry_days", "14.5"), 14.5d) - (i3 / 1440.0d);
                    TextView textView2 = this.sensorAge;
                    StringBuilder sb2 = new StringBuilder();
                    sb2.append(d >= BgReading.BESTOFFSET ? getResources().getQuantityString(2131623957, (int) d, JoH.qs(d, 1)) : getString(2131756285));
                    sb2.append(str);
                    textView2.setText(sb2.toString());
                } catch (Exception e) {
                    Log.e(TAG, "expiry calculation: " + e);
                    this.sensorAge.setText(getString(2131755552));
                }
            }
            this.sensorAge.setVisibility(0);
            if (i3 < 1440) {
                this.sensorAge.setTextColor(-256);
            } else if (i3 < 17280) {
                this.sensorAge.setTextColor(-16711936);
            } else {
                this.sensorAge.setTextColor(-65536);
            }
        } else {
            this.sensorAge.setVisibility(8);
        }
        if (blockTouches) {
            this.sensorAge.setText("SCANNING.. DISPLAY LOCKED!");
            this.sensorAge.setVisibility(0);
            this.sensorAge.setTextColor(-16711936);
        }
        if ((this.currentBgValueText.getPaintFlags() & 16) > 0) {
            TextView textView3 = this.currentBgValueText;
            textView3.setPaintFlags(textView3.getPaintFlags() & (-17));
            TextView textView4 = this.dexbridgeBattery;
            textView4.setPaintFlags(textView4.getPaintFlags() & (-17));
            if (get_follower()) {
                GcmActivity.requestPing();
            }
        }
        BgReading lastNoSenssor = BgReading.lastNoSenssor();
        boolean z = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("predictive_bg", false);
        if (this.isBTShare) {
            z = false;
        }
        if (lastNoSenssor != null) {
            if (lastNoSenssor.raw_data != BgReading.BESTOFFSET && lastNoSenssor.raw_data * 2.0d == lastNoSenssor.filtered_data && JoH.ratelimit("g5-corrupt-data-warning", 1200)) {
                toaststaticnext(getString(2131756900) + lastNoSenssor.raw_data);
            }
            displayCurrentInfoFromReading(lastNoSenssor, z);
        } else {
            this.display_delta = "";
        }
        if (Pref.getBoolean("extra_status_line", false)) {
            this.extraStatusLineText.setText(StatusLine.extraStatusLine());
            this.extraStatusLineText.setVisibility(0);
        } else {
            this.extraStatusLineText.setText("");
            this.extraStatusLineText.setVisibility(8);
        }
    }

    public static long stale_data_millis() {
        return DexCollectionType.getDexCollectionType() == DexCollectionType.LibreAlarm ? 780000L : 660000L;
    }

    private void displayCurrentInfoFromReading(BgReading bgReading, boolean z) {
        BestGlucose.DisplayGlucose displayGlucose;
        double activePrediction;
        String str;
        double d;
        boolean z2;
        String str2;
        if (bgReading == null || (displayGlucose = BestGlucose.getDisplayGlucose()) == null) {
            return;
        }
        String str3 = displayGlucose.delta_arrow;
        if ((new Date().getTime() - stale_data_millis()) - bgReading.timestamp > 0) {
            this.notificationText.setText(2131756372);
            if (!z) {
                activePrediction = displayGlucose.mgdl;
            } else {
                activePrediction = BgReading.estimated_bg(bgReading.timestamp + 42000);
            }
            this.currentBgValueText.setText(this.bgGraphBuilder.unitized_string(activePrediction));
            TextView textView = this.currentBgValueText;
            textView.setPaintFlags(textView.getPaintFlags() | 16);
            TextView textView2 = this.dexbridgeBattery;
            textView2.setPaintFlags(textView2.getPaintFlags() | 16);
            z2 = true;
            d = BgReading.BESTOFFSET;
        } else {
            if (this.notificationText.getText().length() == 0) {
                this.notificationText.setTextColor(-1);
            }
            boolean z3 = Pref.getBoolean("bg_from_filtered", false);
            String str4 = "";
            if (!z) {
                double d2 = displayGlucose.mgdl;
                this.currentBgValueText.setTypeface(null, 0);
                if (z3 && BgGraphBuilder.last_noise < 100.0d && Pref.getBoolean("bg_compensate_noise", false)) {
                    Pref.setBoolean("bg_from_filtered", false);
                    z3 = false;
                }
                if (BestGlucose.compensateNoise()) {
                    d2 = BgGraphBuilder.best_bg_estimate;
                    d = d2 - BgGraphBuilder.last_bg_estimate;
                    str3 = BgReading.slopeToArrowSymbol(d / 5.0d);
                    this.currentBgValueText.setTypeface(null, 2);
                    str2 = "⚠";
                    if (BgGraphBuilder.last_noise > 200.0d && DexCollectionType.hasFiltered()) {
                        z3 = true;
                    }
                } else {
                    str2 = "";
                    d = BgReading.BESTOFFSET;
                }
                if (z3) {
                    TextView textView3 = this.currentBgValueText;
                    textView3.setPaintFlags(textView3.getPaintFlags() | 8);
                    d2 = bgReading.filtered_calculated_value;
                } else {
                    TextView textView4 = this.currentBgValueText;
                    textView4.setPaintFlags(textView4.getPaintFlags() & (-9));
                }
                String unitized_string = this.bgGraphBuilder.unitized_string(d2);
                if (bgReading.hide_slope || z3) {
                    str3 = "";
                }
                TextView textView5 = this.currentBgValueText;
                StringBuilder sb = new StringBuilder();
                sb.append(unitized_string);
                if (this.itr == null) {
                    str4 = " " + str3;
                }
                sb.append(str4);
                textView5.setText(sb.toString());
                activePrediction = d2;
                str4 = str2;
            } else {
                activePrediction = BgReading.activePrediction();
                String unitized_string2 = this.bgGraphBuilder.unitized_string(activePrediction);
                TextView textView6 = this.currentBgValueText;
                StringBuilder sb2 = new StringBuilder();
                sb2.append(unitized_string2);
                if (this.itr == null) {
                    str = " " + BgReading.activeSlopeArrow();
                } else {
                    str = "";
                }
                sb2.append(str);
                textView6.setText(sb2.toString());
                d = BgReading.BESTOFFSET;
            }
            if (str4.length() > 0) {
                this.currentBgValueText.setText(str4 + ((Object) this.currentBgValueText.getText()));
            }
            z2 = false;
        }
        int currentTimeMillis = ((int) (System.currentTimeMillis() - bgReading.timestamp)) / UsbId.SILABS_CP2102;
        if (!this.small_width || this.notificationText.length() > 0) {
            this.notificationText.append("\n");
        }
        if (!this.small_width) {
            this.notificationText.append(MessageFormat.format(getString(2131755830), Integer.valueOf(currentTimeMillis)));
        } else {
            this.notificationText.append(currentTimeMillis + getString(2131756395));
            this.currentBgValueText.setPadding(0, 0, 0, 0);
        }
        if (this.small_screen && this.currentBgValueText.getText().length() > 4) {
            this.currentBgValueText.setTextSize(25.0f);
        }
        ITrendArrow iTrendArrow = this.itr;
        if (iTrendArrow != null) {
            iTrendArrow.update((bgReading.hide_slope || z2) ? null : Double.valueOf(displayGlucose.slope * 60000.0d));
        }
        List<BgReading> latest = BgReading.latest(2, is_follower);
        if (latest != null && latest.size() == 2) {
            this.display_delta = displayGlucose.unitized_delta;
            if (BestGlucose.compensateNoise()) {
                this.display_delta = this.bgGraphBuilder.unitizedDeltaStringRaw(true, true, d);
                addDisplayDelta();
                if (!Pref.getBoolean("show_noise_workings", false)) {
                    this.notificationText.append("\n" + String.format(xdrip.gs(2131755918), BgGraphBuilder.noiseString(BgGraphBuilder.last_noise)));
                }
            } else {
                addDisplayDelta();
            }
        }
        double unitized = this.bgGraphBuilder.unitized(activePrediction);
        BgGraphBuilder bgGraphBuilder = this.bgGraphBuilder;
        if (unitized <= bgGraphBuilder.lowMark) {
            this.currentBgValueText.setTextColor(ColorCache.getCol(ColorCache.X.color_low_bg_values));
        } else if (bgGraphBuilder.unitized(activePrediction) >= this.bgGraphBuilder.highMark) {
            this.currentBgValueText.setTextColor(ColorCache.getCol(ColorCache.X.color_high_bg_values));
        } else {
            this.currentBgValueText.setTextColor(ColorCache.getCol(ColorCache.X.color_inrange_bg_values));
        }
        if (!Pref.getBooleanDefaultFalse("display_glucose_from_plugin") || PluggableCalibration.getCalibrationPluginFromPreferences() == null) {
            return;
        }
        this.currentBgValueText.setText(getString(2131755982) + ((Object) this.currentBgValueText.getText()));
    }

    private void HebrewAppendDisplayData() {
        String charSequence = this.notificationText.getText().toString();
        String str = TAG;
        Log.d(str, "original_text = " + HexDump.dumpHexString(charSequence.getBytes()));
        if (charSequence.length() >= 1 && charSequence.charAt(0) == '\n') {
            Log.d(str, "removing first and appending " + this.display_delta);
            this.notificationText.setText(this.display_delta + "  " + charSequence.substring(1));
            return;
        }
        this.notificationText.setText(this.display_delta + "  " + charSequence);
    }

    private void addDisplayDelta() {
        if (BgGraphBuilder.isXLargeTablet(getApplicationContext())) {
            if (Locale.getDefault().getLanguage().equals("iw")) {
                HebrewAppendDisplayData();
                return;
            } else {
                this.notificationText.append("  ");
                this.notificationText.append(this.display_delta);
                return;
            }
        }
        this.notificationText.append("\n");
        this.notificationText.append(this.display_delta);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent motionEvent) {
        if (blockTouches) {
            return true;
        }
        try {
            return super.dispatchTouchEvent(motionEvent);
        } catch (Exception unused) {
            return false;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(2131558407, menu);
        if (!Pref.getBoolean("wear_sync", false)) {
            menu.removeItem(2131296331);
            menu.removeItem(2131296338);
        }
        if (!Pref.getBoolean("wear_sync", false) && !Pref.getBoolean("pref_amazfit_enable_key", false)) {
            menu.removeItem(2131296335);
        }
        MenuItem findItem = menu.findItem(2131296343);
        if (Pref.getBoolean("bg_to_speech_shortcut", false)) {
            findItem.setVisible(true);
            if (Pref.getBoolean("bg_to_speech", false)) {
                findItem.setChecked(true);
            } else {
                findItem.setChecked(false);
            }
        } else {
            findItem.setVisible(false);
        }
        boolean z = DexCollectionType.hasWifi() ? Pref.getBoolean("plus_extra_features", false) : false;
        menu.findItem(2131296989).setVisible(z);
        menu.findItem(2131296835).setVisible(z);
        menu.findItem(2131296524).setVisible(Experience.gotData());
        menu.findItem(2131296992).setVisible(Pref.getBoolean("plus_show_reminders", true) && !this.is_newbie);
        if (!hasLibreblock()) {
            menu.findItem(2131296706).setVisible(false);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onNewIntent(Intent intent) {
        processIncomingBundle(intent.getExtras());
    }

    private synchronized void showcasemenu(int i) {
        ViewTarget viewTarget;
        String str;
        String str2;
        ViewTarget viewTarget2;
        ShowcaseView showcaseView = myShowcase;
        if (showcaseView == null || !showcaseView.isShowing()) {
            if (ShotStateStore.hasShot(i)) {
                return;
            }
            int i2 = 90;
            int i3 = 14;
            try {
                if (i != 1) {
                    if (i == 11) {
                        viewTarget2 = new ViewTarget(2131296413, this);
                        str2 = getString(2131756792);
                        str = getString(2131755815);
                    } else if (i == 3) {
                        viewTarget = new ViewTarget(2131296415, this);
                        str2 = "";
                        viewTarget2 = viewTarget;
                        str = "";
                    } else if (i == 4) {
                        viewTarget2 = new ViewTarget(2131296416, this);
                        str2 = getString(2131756927);
                        str = getString(2131756369);
                    } else if (i == 5) {
                        viewTarget2 = new ViewTarget(2131296414, this);
                        str2 = getString(2131756174);
                        str = getString(2131756368);
                    } else if (i == 6) {
                        viewTarget2 = new ViewTarget(2131296413, this);
                        str2 = getString(2131755928);
                        str = getString(2131756367);
                    } else if (i != 7) {
                        viewTarget = null;
                        str2 = "";
                        viewTarget2 = viewTarget;
                        str = "";
                    } else {
                        viewTarget2 = new ViewTarget(2131296413, this);
                        str2 = getString(2131756870);
                        str = getString(2131755823);
                    }
                    i2 = 0;
                    i3 = 0;
                } else {
                    for (View view : ((Toolbar) findViewById(2131296797)).getTouchables()) {
                        Log.d("jamhorham showcase", view.getClass().getSimpleName());
                        if (view.getClass().getSimpleName().equals("OverflowMenuButton")) {
                            viewTarget = new ViewTarget(view);
                            break;
                        }
                    }
                    viewTarget = null;
                    str2 = "";
                    viewTarget2 = viewTarget;
                    str = "";
                }
                if (viewTarget2 != null) {
                    ShowcaseView build = new ShowcaseView.Builder(this).setTarget(viewTarget2).setStyle(2131820768).setContentTitle(str2).setContentText("\n" + str).setShowcaseDrawer(new JamorhamShowcaseDrawer(getResources(), getTheme(), i2, i3)).singleShot(i).build();
                    myShowcase = build;
                    build.setBackgroundColor(0);
                    myShowcase.show();
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception in showcase: " + e.toString());
            }
        }
    }

    public void shareMyConfig(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) DisplayQRCode.class));
    }

    public void exportDatabase(MenuItem menuItem) {
        new AsyncTask<Void, Void, String>() {
            @Override
            public String doInBackground(Void... voidArr) {
                if (ContextCompat.checkSelfPermission(Home.this, "android.permission.READ_EXTERNAL_STORAGE") != 0) {
                    ActivityCompat.requestPermissions(Home.this, new String[]{"android.permission.READ_EXTERNAL_STORAGE"}, 0);
                    return null;
                }
                return DatabaseUtil.saveSql(Home.this.getBaseContext());
            }

            @Override
            public void onPostExecute(String str) {
                super.onPostExecute((AnonymousClass8) str);
                if (str != null) {
                    Home.snackBar(2131756315, Home.this.getString(2131755554) + str, Home.this.makeSnackBarUriLauncher(Uri.fromFile(new File(str)), Home.this.getString(2131756317)), Home.this);
                    Home.this.startActivity(new Intent(xdrip.getAppContext(), (Class<?>) SdcardImportExport.class).putExtra("backup", "now").setFlags(268435456));
                    return;
                }
                Toast.makeText(Home.this, 2131755383, 1).show();
            }
        }.execute(new Void[0]);
    }

    public void restoreDatabase(MenuItem menuItem) {
        startActivity(new Intent(this, (Class<?>) ImportDatabaseActivity.class));
    }

    public void exportCSVasSiDiary(MenuItem menuItem) {
        long j = Pref.getLong("sidiary_last_exportdate", 0L);
        final GregorianCalendar gregorianCalendar = new GregorianCalendar();
        DatePickerFragment datePickerFragment = new DatePickerFragment();
        if (j > 0) {
            datePickerFragment.setInitiallySelectedDate(j);
        }
        datePickerFragment.setAllowFuture(false);
        datePickerFragment.setTitle(getString(2131756371));
        datePickerFragment.setDateCallback(new ProfileAdapter.DatePickerCallbacks() {
            @Override
            public void onDateSet(int i, int i2, int i3) {
                gregorianCalendar.set(i, i2, i3);
                gregorianCalendar.set(11, 0);
                gregorianCalendar.set(12, 0);
                gregorianCalendar.set(13, 0);
                gregorianCalendar.set(14, 0);
                new AsyncTask<Void, Void, String>() {
                    @Override
                    public String doInBackground(Void... voidArr) {
                        if (ContextCompat.checkSelfPermission(Home.this, "android.permission.READ_EXTERNAL_STORAGE") != 0) {
                            ActivityCompat.requestPermissions(Home.this, new String[]{"android.permission.READ_EXTERNAL_STORAGE"}, 0);
                            return null;
                        }
                        return DatabaseUtil.saveCSV(Home.this.getBaseContext(), gregorianCalendar.getTimeInMillis());
                    }

                    @Override
                    public void onPostExecute(String str) {
                        super.onPostExecute((AnonymousClass1) str);
                        if (str != null) {
                            Pref.setLong("sidiary_last_exportdate", System.currentTimeMillis());
                            Home.snackBar(2131756315, Home.this.getString(2131755554) + str, Home.this.makeSnackBarUriLauncher(Uri.fromFile(new File(str)), Home.this.getString(2131756317)), Home.this);
                            return;
                        }
                        Toast.makeText(Home.this, xdrip.gs(2131755382), 1).show();
                    }
                }.execute(new Void[0]);
            }
        });
        datePickerFragment.show(getFragmentManager(), "DatePicker");
    }

    public void settingsSDcardExport(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) SdcardImportExport.class));
    }

    public void showMapFromMenu(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) MapsActivity.class));
    }

    public void showHelpFromMenu(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) HelpActivity.class));
    }

    public void showRemindersFromMenu(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) Reminders.class));
    }

    public void showAssistFromMenu(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) EmergencyAssistActivity.class));
    }

    public void parakeetSetupMode(MenuItem menuItem) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(2131755153);
        builder.setPositiveButton(2131757077, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.this.lambda$parakeetSetupMode$43(dialogInterface, i);
            }
        });
        builder.setNegativeButton(2131755919, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.lambda$parakeetSetupMode$44(dialogInterface, i);
            }
        });
        builder.create().show();
    }

    public void lambda$parakeetSetupMode$43(DialogInterface dialogInterface, int i) {
        ParakeetHelper.parakeetSetupMode(getApplicationContext());
    }

    public void resendGlucoseToWatch(MenuItem menuItem) {
        WatchUpdaterService.startServiceAndResendData(0L);
        if (Pref.getBooleanDefaultFalse("pref_amazfit_enable_key")) {
            Amazfitservice.start("xDrip_synced_SGV_data");
        }
    }

    public void openSettingsOnWatch(MenuItem menuItem) {
        startService(new Intent(this, (Class<?>) WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_OPEN_SETTINGS));
    }

    public void resetWearDb(MenuItem menuItem) {
        startService(new Intent(this, (Class<?>) WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_RESET_DB));
    }

    public void undoButtonClick(View view) {
        if (UndoRedo.undoNextItem()) {
            staticRefreshBGCharts();
        }
    }

    public void redoButtonClick(View view) {
        if (UndoRedo.redoNextItem()) {
            staticRefreshBGCharts();
        }
    }

    public void noteDefaultMethodChanged(View view) {
        Pref.setBoolean("default_to_voice_notes", !Pref.getBooleanDefaultFalse("default_to_voice_notes"));
    }

    public void showNoteTextInputDialog(View view) {
        showNoteTextInputDialog(view, JoH.tsl(), -1.0d);
    }

    public void showNoteTextInputDialog(View view, long j) {
        showNoteTextInputDialog(view, j, -1.0d);
    }

    public void showNoteTextInputDialog(View view, final long j, final double d) {
        Log.d(TAG, "showNoteTextInputDialog: ts:" + j + " pos:" + d);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View inflate = getLayoutInflater().inflate(2131493028, (ViewGroup) null);
        builder.setView(inflate);
        final EditText editText = (EditText) inflate.findViewById(2131297145);
        ((CheckBox) inflate.findViewById(2131296538)).setChecked(Pref.getBooleanDefaultFalse("default_to_voice_notes"));
        builder.setTitle(2131756909);
        builder.setPositiveButton(2131755480, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.this.lambda$showNoteTextInputDialog$46(editText, j, d, dialogInterface, i);
            }
        });
        builder.setNegativeButton(getString(2131755280), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                Home.this.lambda$showNoteTextInputDialog$47(dialogInterface, i);
            }
        });
        if (Treatments.byTimestamp(j, 150000) != null) {
            builder.setNeutralButton(2131755418, new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    Home.lambda$showNoteTextInputDialog$50(j, dialogInterface, i);
                }
            });
        }
        this.dialog = builder.create();
        editText.setInputType(1);
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public final void onFocusChange(View view2, boolean z) {
                Home.this.lambda$showNoteTextInputDialog$51(view2, z);
            }
        });
        this.dialog.show();
    }

    public void lambda$showNoteTextInputDialog$46(EditText editText, final long j, double d, DialogInterface dialogInterface, int i) {
        String trim = editText.getText().toString().trim();
        Log.d(TAG, "Got treatment note: " + trim);
        Treatments.create_note(trim, j, d);
        staticRefreshBGCharts();
        if (trim.length() > 0) {
            snackBar(2131755076, getString(2131755078) + ":    " + trim, new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    Home.lambda$showNoteTextInputDialog$45(j, view);
                }
            }, mActivity);
        }
        if (Pref.getBooleanDefaultFalse("default_to_voice_notes")) {
            showcasemenu(6);
        }
    }

    public static void lambda$showNoteTextInputDialog$45(long j, View view) {
        startHomeWithExtra(xdrip.getAppContext(), "CREATE_TREATMENT_NOTE", Long.toString(j), "-1");
    }

    public void lambda$showNoteTextInputDialog$47(DialogInterface dialogInterface, int i) {
        if (Pref.getBooleanDefaultFalse("default_to_voice_notes")) {
            showcasemenu(6);
        }
    }

    public static void lambda$showNoteTextInputDialog$50(final long j, DialogInterface dialogInterface, int i) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle(xdrip.gs(2131755368));
        builder.setMessage(xdrip.gs(2131755155));
        builder.setPositiveButton(xdrip.gs(2131757074), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface2, int i2) {
                Home.lambda$showNoteTextInputDialog$48(j, dialogInterface2, i2);
            }
        });
        builder.setNegativeButton(xdrip.gs(2131755900), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface2, int i2) {
                dialogInterface2.dismiss();
            }
        });
        builder.create().show();
    }

    public static void lambda$showNoteTextInputDialog$48(long j, DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
        Treatments.delete_by_timestamp(j, 150000, true);
        staticRefreshBGCharts();
        JoH.static_toast_short(xdrip.gs(2131755423));
    }

    public void lambda$showNoteTextInputDialog$51(View view, boolean z) {
        AlertDialog alertDialog;
        if (!z || (alertDialog = this.dialog) == null) {
            return;
        }
        alertDialog.getWindow().setSoftInputMode(5);
    }

    public void doBackFillBroadcast(MenuItem menuItem) {
        GcmActivity.syncBGTable2();
        toast(xdrip.gs(2131756421));
    }

    public void deleteAllBG(MenuItem menuItem) {
        BgReading.deleteALL();
        toast(xdrip.gs(2131755424));
        staticRefreshBGCharts();
    }

    public void checkForUpdate(MenuItem menuItem) {
        if (JoH.ratelimit("manual-update-check", 5)) {
            toast(getString(2131755319));
            UpdateActivity.last_check_time = -1L;
            UpdateActivity.checkForAnUpdate(getApplicationContext(), true);
        }
    }

    public void toggleSpeakReadings(MenuItem menuItem) {
        Pref.toggleBoolean("bg_to_speech");
        invalidateOptionsMenu();
        if (Pref.getBooleanDefaultFalse("bg_to_speech")) {
            BgToSpeech.testSpeech();
        }
    }

    public void sendFeedback(MenuItem menuItem) {
        startActivity(new Intent(getApplicationContext(), (Class<?>) SendFeedBack.class));
    }

    @Override
    public boolean onKeyDown(int i, KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        if ((keyCode == 24 || keyCode == 25 || keyCode == 164) && JoH.quietratelimit("button-press", 5) && Pref.getBooleanDefaultFalse("buttons_silence_alert") && ActiveBgAlert.getOnly() != null) {
            AlertPlayer.getPlayer().Snooze(xdrip.getAppContext(), -1);
            JoH.static_toast_long(getString(2131756391));
            UserError.Log.ueh(TAG, "Snoozing alert due to volume button press");
        }
        return super.onKeyDown(i, keyEvent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        return super.onOptionsItemSelected(menuItem);
    }

    public void initializeGraphicTrendArrow() {
        if (this.homeShelf.get("graphic_trend_arrow")) {
            if (this.itr == null) {
                this.itr = TrendArrowFactory.create((ImageView) findViewById(2131297146));
            }
        } else {
            ITrendArrow iTrendArrow = this.itr;
            if (iTrendArrow != null) {
                iTrendArrow.update(null);
                this.itr = null;
            }
        }
    }

    public static double convertToMgDlIfMmol(double d) {
        return !Pref.getString("units", "mgdl").equals("mgdl") ? d * 18.0182d : d;
    }

    public static void snackBar(int i, String str, View.OnClickListener onClickListener, Activity activity) {
        Snackbar.make(activity.findViewById(R.id.content), str, 0).setAction(i, onClickListener).show();
    }

    public static void staticBlockUI(Activity activity, boolean z) {
        blockTouches = z;
        if (z) {
            JoH.lockOrientation(activity);
        } else {
            JoH.releaseOrientation(activity);
        }
    }

    private class MainChartViewPortListener implements ViewportChangeListener {
        private MainChartViewPortListener() {
        }

        public synchronized void onViewportChanged(Viewport viewport) {
            if (!Home.this.updatingPreviewViewport) {
                Home.this.updatingChartViewport = true;
                Home.this.previewChart.setZoomType(ZoomType.HORIZONTAL);
                Home.this.previewChart.setCurrentViewport(viewport);
                Home.this.updatingChartViewport = false;
            }
        }
    }

    public class PreviewChartViewportListener implements ViewportChangeListener {
        public PreviewChartViewportListener() {
        }

        public synchronized void onViewportChanged(Viewport viewport) {
            if (!Home.this.updatingChartViewport) {
                Home.this.updatingPreviewViewport = true;
                Home.this.chart.setZoomType(ZoomType.HORIZONTAL);
                Home.this.chart.setCurrentViewport(viewport);
                Home.this.tempViewport = viewport;
                Home.this.updatingPreviewViewport = false;
            }
            if (Home.this.updateStuff) {
                Home.this.holdViewport.set(viewport.left, viewport.top, viewport.right, viewport.bottom);
            }
        }
    }

    public void showArrowConfigurator(View view, boolean z, boolean z2) {
        if (this.homeShelf.get("arrow_configurator") && z) {
            z = false;
        }
        this.homeShelf.set("arrow_configurator", z);
        try {
            View configurator = this.itr.getConfigurator();
            try {
                ((ViewGroup) configurator.getParent()).removeView(configurator);
            } catch (NullPointerException unused) {
            }
            ViewGroup viewGroup = (ViewGroup) view.getParent().getParent();
            viewGroup.removeView(configurator);
            if (z && configurator != null) {
                viewGroup.addView(configurator);
            }
        } catch (NullPointerException unused2) {
        }
        if (z2) {
            staticRefreshBGCharts();
        }
    }

    public int arrowSelectionCurrent() {
        return TrendArrowFactory.getArrayPosition();
    }

    public void arrowSelectionChanged(AdapterView<?> adapterView, View view, int i, long j) {
        if (TrendArrowFactory.setType(i)) {
            showArrowConfigurator(view, false, false);
            this.itr = null;
            initializeGraphicTrendArrow();
            showArrowConfigurator(view, true, true);
        }
    }

    private void testGraphicalTrendArrow() {
        if (this.itr != null) {
            JoH.runOnUiThreadDelayed(new Runnable() {
                @Override
                public final void run() {
                    Home.this.lambda$testGraphicalTrendArrow$52();
                }
            }, 1000L);
            JoH.runOnUiThreadDelayed(new Runnable() {
                @Override
                public final void run() {
                    Home.this.lambda$testGraphicalTrendArrow$53();
                }
            }, 5000L);
            JoH.runOnUiThreadDelayed(new Runnable() {
                @Override
                public final void run() {
                    Home.this.lambda$testGraphicalTrendArrow$54();
                }
            }, 9000L);
            JoH.runOnUiThreadDelayed(new Runnable() {
                @Override
                public final void run() {
                    Home.this.lambda$testGraphicalTrendArrow$55();
                }
            }, 13000L);
        }
    }

    public void lambda$testGraphicalTrendArrow$52() {
        this.itr.update(Double.valueOf(5.0d));
    }

    public void lambda$testGraphicalTrendArrow$53() {
        this.itr.update(Double.valueOf(-5.0d));
    }

    public void lambda$testGraphicalTrendArrow$54() {
        this.itr.update(Double.valueOf(-0.0d));
    }

    public void lambda$testGraphicalTrendArrow$55() {
        this.itr.update(Double.valueOf(5.0d));
    }

    public View.OnClickListener makeSnackBarUriLauncher(final Uri uri, final String str) {
        return new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                Home.this.lambda$makeSnackBarUriLauncher$56(uri, str, view);
            }
        };
    }

    public void lambda$makeSnackBarUriLauncher$56(Uri uri, String str, View view) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.SEND");
        intent.putExtra("android.intent.extra.STREAM", uri);
        intent.setType("application/octet-stream");
        startActivity(Intent.createChooser(intent, str));
    }

    public static PendingIntent getHomePendingIntent() {
        return PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), (Class<?>) Home.class), 134217728);
    }

    @Override
    public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) {
        if (i == 9104 && strArr.length > 0 && iArr.length > 0 && strArr[0].equals("android.permission.WRITE_EXTERNAL_STORAGE") && iArr[0] == 0) {
            SdcardImportExport.restoreSettingsNow(this);
        }
    }
}