导航菜单

页面标题

页面副标题

Harvest v2.32 - HarvestActivity.java 源代码

正在查看: Harvest v2.32 应用的 HarvestActivity.java JAVA 源代码文件

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


package com.ufields.tracking;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.itextpdf.text.xml.xmp.DublinCoreProperties;
import com.itextpdf.text.xml.xmp.XmpWriter;
import com.ufields.tracking.Adapters.DrawerItemCustomAdapter;
import com.ufields.tracking.Adapters.ListViewAdapterHarvest;
import com.ufields.tracking.App.AppUtils;
import com.ufields.tracking.App.EndPoints;
import com.ufields.tracking.App.MyApplication;
import com.ufields.tracking.DataModels.HarvestDataModel;
import com.ufields.tracking.DataModels.HarvestPackageModel;
import com.ufields.tracking.DataModels.MenuDataModel;
import com.ufields.tracking.DataModels.OrganizationEmployee;
import com.ufields.tracking.Databases.PendingTracking;
import com.ufields.tracking.HarvestActivity;
import com.ufields.tracking.Services.SendingDataSchedulerService;
import com.ufields.tracking.Services.SendingDataService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import kotlin.jvm.internal.ByteCompanionObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class HarvestActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback {
    private static final String MIME_TEXT_PLAIN = "text/plain";
    private static final String TAG = "NfcDemo";
    static final String UPDATE_ACTION = "UPDATE_ACTION";
    public static final int addNewHarvestCode = 102;
    public static final int updateHarvestCode = 101;

    @BindView(R.id.listViewHarvestInProgress)
    ListView LvHarvest;
    private ListViewAdapterHarvest LvaHarvest;

    @BindView(R.id.addHarvest)
    FloatingActionButton addHarvest;
    private Context ctx;

    @BindView(R.id.datePicker)
    TextView datePicker;
    ArrayList<MenuDataModel> drawerItem;
    private DrawerItemCustomAdapter drawerItemCustomAdapter;

    @BindView(R.id.drawerLayoutProduction)
    DrawerLayout drawerLayout;
    private MenuItem english;
    private ArrayAdapter<String> fieldNameAdapter;
    private MenuItem french;

    @BindView(R.id.listViewMenuProduction)
    ListView listViewMenu;
    private SendingDataService mSendingService;
    private Intent mServiceIntent;

    @BindView(R.id.noHarvestEmptyTV)
    TextView noHarvestEmptyTV;
    private Dialog pDialog;
    private ProgressBar progressBar;

    @BindView(R.id.pulltorefresh)
    SwipeRefreshLayout refreshLayout;

    @BindView(R.id.scrollView)
    ScrollView scrollView;
    private TextView setMessage;

    @BindView(R.id.containerToolbar)
    LinearLayout snack;
    private MenuItem spanish;
    private ArrayAdapter<String> subFieldNameAdapter;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private TextView toolbarTitle;
    private UpdateReceiver updateReceiver;
    private Handler workerThread;
    private int selectedPos = -1;
    private NfcAdapter mNfcAdapter = null;
    private ArrayList<HarvestDataModel> arrayListHarvest = new ArrayList<>();
    private String cropName = "";
    private String cultivarName = "";
    private ArrayList<String> harvestIds = new ArrayList<>();
    private ArrayList<String> fieldList = new ArrayList<>();
    private ArrayList<String> subFieldList = new ArrayList<>();
    private HashMap<String, String> fieldSubFieldMap = new HashMap<>();
    private HashMap<String, ArrayList<String>> subFieldMap = new HashMap<>();
    private HashMap<String, String> cropMap = new HashMap<>();
    private HashMap<String, String> cultivarMap = new HashMap<>();
    private HashMap<String, String> cropCultivarFieldMap = new HashMap<>();
    private HashMap<String, String> cropCultivarSubFieldMap = new HashMap<>();
    private Boolean isQrScannerAvailable = false;

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter adapter = listView.getAdapter();
        if (adapter == null) {
            return;
        }
        int makeMeasureSpec = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), 0);
        View view = null;
        int i = 0;
        for (int i2 = 0; i2 < adapter.getCount(); i2++) {
            view = adapter.getView(i2, view, listView);
            if (i2 == 0) {
                view.setLayoutParams(new ViewGroup.LayoutParams(makeMeasureSpec, -2));
            }
            view.measure(makeMeasureSpec, 0);
            i += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams layoutParams = listView.getLayoutParams();
        layoutParams.height = i + (listView.getDividerHeight() * (adapter.getCount() - 1));
        listView.setLayoutParams(layoutParams);
    }

    public static void setupForegroundDispatch(NfcAdapter.ReaderCallback readerCallback, Activity activity, NfcAdapter nfcAdapter) {
        Bundle bundle = new Bundle();
        bundle.putInt("presence", 1000);
        nfcAdapter.enableReaderMode(activity, readerCallback, 15, bundle);
    }

    public static void stopForegroundDispatch(Activity activity, NfcAdapter nfcAdapter) {
        nfcAdapter.disableReaderMode(activity);
    }

    public Context getCtx() {
        return this.ctx;
    }

    protected void onCreate(Bundle bundle) {
        JSONObject jSONObject;
        AppUtils.setConfigChange(this);
        super.onCreate(bundle);
        this.ctx = this;
        setContentView(R.layout.activity_harvest);
        ButterKnife.bind(this);
        this.workerThread = new Handler();
        this.updateReceiver = new UpdateReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATE_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(this.updateReceiver, intentFilter);
        this.toolbarTitle = (TextView) this.toolbar.findViewById(R.id.toolbarText);
        this.mSendingService = new SendingDataService(getCtx());
        this.mServiceIntent = new Intent(getCtx(), this.mSendingService.getClass());
        this.datePicker.setText(getCurrentDate());
        Dialog dialog = new Dialog(this);
        this.pDialog = dialog;
        dialog.setCanceledOnTouchOutside(false);
        this.pDialog.requestWindowFeature(1);
        this.pDialog.setContentView(R.layout.progress_dialog);
        this.pDialog.setTitle("");
        this.progressBar = (ProgressBar) this.pDialog.findViewById(R.id.progress);
        this.setMessage = (TextView) this.pDialog.findViewById(R.id.message);
        setupToolbar();
        ArrayList<MenuDataModel> arrayList = new ArrayList<>();
        this.drawerItem = arrayList;
        arrayList.add(0, new MenuDataModel(R.drawable.harvest32, getResources().getString(R.string.harvest)));
        this.drawerItem.add(1, new MenuDataModel(R.drawable.employee, getResources().getString(R.string.employees)));
        this.drawerItem.add(2, new MenuDataModel(R.drawable.logout, getResources().getString(R.string.logout)));
        this.drawerItem.add(3, new MenuDataModel(R.drawable.version, getResources().getString(R.string.appversion) + " 2.32"));
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(true);
        this.drawerItemCustomAdapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item, this.drawerItem);
        try {
            jSONObject = new JSONObject(MyApplication.getInstance().getPrefManager().getOrganizationEmployee().getOrganizationInfo());
        } catch (JSONException e) {
            e.printStackTrace();
            jSONObject = null;
        }
        View inflate = getLayoutInflater().inflate(R.layout.list_view_header, (ViewGroup) null);
        try {
            ((TextView) inflate.findViewById(2131362342)).setText(jSONObject.getString("name"));
        } catch (JSONException e2) {
            e2.printStackTrace();
        }
        this.listViewMenu.addHeaderView(inflate);
        this.listViewMenu.setAdapter((ListAdapter) this.drawerItemCustomAdapter);
        this.listViewMenu.setOnItemClickListener(new DrawerItemClickListener());
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setupDrawerToggle();
        if (isNetworkAvailable()) {
            new GetAccessDetail().execute(new String[0]);
        } else {
            updateHarvest();
            if (Build.VERSION.SDK_INT >= 21) {
                scheduleJob();
            }
        }
        this.mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        this.refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public final void onRefresh() {
                HarvestActivity.this.m14lambda$onCreate$0$comufieldstrackingHarvestActivity();
            }
        });
        this.datePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                HarvestActivity.this.m15lambda$onCreate$1$comufieldstrackingHarvestActivity(view);
            }
        });
        this.addHarvest.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                HarvestActivity.this.m16lambda$onCreate$2$comufieldstrackingHarvestActivity(view);
            }
        });
        ListViewAdapterHarvest listViewAdapterHarvest = new ListViewAdapterHarvest(getApplicationContext(), this.arrayListHarvest);
        this.LvaHarvest = listViewAdapterHarvest;
        this.LvHarvest.setAdapter((ListAdapter) listViewAdapterHarvest);
        this.LvHarvest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public final void onItemClick(AdapterView adapterView, View view, int i, long j) {
                HarvestActivity.this.m17lambda$onCreate$3$comufieldstrackingHarvestActivity(adapterView, view, i, j);
            }
        });
    }

    void m14lambda$onCreate$0$comufieldstrackingHarvestActivity() {
        setCurrentDate();
        if (isNetworkAvailable()) {
            new OrganizationLogin().execute(new String[0]);
            this.refreshLayout.setRefreshing(false);
        } else {
            this.refreshLayout.setRefreshing(false);
            updateHarvest();
        }
    }

    void m15lambda$onCreate$1$comufieldstrackingHarvestActivity(View view) {
        try {
            datePicker();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    void m16lambda$onCreate$2$comufieldstrackingHarvestActivity(View view) {
        goToAddHarvest();
    }

    void m17lambda$onCreate$3$comufieldstrackingHarvestActivity(AdapterView adapterView, View view, int i, long j) {
        this.selectedPos = i;
        Intent intent = new Intent(getApplicationContext(), (Class<?>) HarvestInProgressActivity.class);
        intent.putExtra("fieldName", this.arrayListHarvest.get(i).getFieldName());
        intent.putExtra(DublinCoreProperties.DATE, this.arrayListHarvest.get(i).getDate());
        intent.putExtra("employeeCount_Average", this.arrayListHarvest.get(i).getEmployeeCount_Average());
        intent.putExtra("quantity", this.arrayListHarvest.get(i).getHarvestQuantity());
        intent.putExtra("duration", this.arrayListHarvest.get(i).getDuration());
        intent.putExtra("fieldType", this.arrayListHarvest.get(i).getFieldType());
        intent.putExtra("fieldId", this.arrayListHarvest.get(i).getFiledId());
        intent.putExtra("cropId", this.arrayListHarvest.get(i).getCropId());
        intent.putExtra("cultivarId", this.arrayListHarvest.get(i).getCultivarId());
        intent.putExtra("organizationId", this.arrayListHarvest.get(i).getOrganizationId());
        intent.putExtra("harvestId", this.arrayListHarvest.get(i).getHarvestId());
        intent.putExtra("harvestLotNO", this.arrayListHarvest.get(i).getHarvestLot());
        intent.putExtra("defaultPackageId", this.arrayListHarvest.get(i).getDefaultPackageId());
        intent.putExtra("harvestNote", this.arrayListHarvest.get(i).getNotes());
        startActivityForResult(intent, 101);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    public View onCreateView(String str, Context context, AttributeSet attributeSet) {
        return super.onCreateView(str, context, attributeSet);
    }

    public void setCurrentDate() {
        this.datePicker.setText(getCurrentDate());
    }

    private void goToAddHarvest() {
        startActivityForResult(new Intent(getApplicationContext(), (Class<?>) AddNewHarvestActivity.class), 102);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i2 == -1) {
            if (i == 102) {
                String stringExtra = intent.getStringExtra("addDate");
                String trim = this.datePicker.getText().toString().trim();
                if (stringExtra.equalsIgnoreCase(trim)) {
                    new GetHarvestList().execute(trim);
                    return;
                }
                return;
            }
            if (i == 101) {
                String stringExtra2 = intent.getStringExtra("HarvestLot");
                String stringExtra3 = intent.getStringExtra("HarvestNotes");
                String stringExtra4 = intent.getStringExtra("harvestQuantityList");
                int i3 = this.selectedPos;
                if (i3 >= 0) {
                    HarvestDataModel harvestDataModel = this.arrayListHarvest.get(i3);
                    if (harvestDataModel.getHarvestLot().equalsIgnoreCase(stringExtra2) && harvestDataModel.getNotes().equalsIgnoreCase(stringExtra3) && harvestDataModel.getHarvestQuantity().equalsIgnoreCase(stringExtra4)) {
                        return;
                    }
                    harvestDataModel.setHarvestLot(stringExtra2);
                    harvestDataModel.setNotes(stringExtra3);
                    harvestDataModel.setHarvestPackageModelArray((ArrayList) new Gson().fromJson(stringExtra4, new TypeToken<ArrayList<HarvestPackageModel>>() {
                    }.getType()));
                    this.LvaHarvest.updateModel(this.selectedPos, harvestDataModel);
                }
            }
        }
    }

    public void showSnackBar(String str) {
        Snackbar make = Snackbar.make(this.snack, str, 0);
        View view = make.getView();
        view.setBackgroundColor(Color.parseColor("#D0021B"));
        TextView textView = (TextView) view.findViewById(R.id.snackbar_text);
        textView.setGravity(17);
        textView.setTextColor(Color.parseColor("#FFFFFF"));
        textView.setAllCaps(true);
        make.show();
    }

    public void scheduleJob() {
        if (Build.VERSION.SDK_INT >= 24) {
            ((JobScheduler) getSystemService("jobscheduler")).schedule(new JobInfo.Builder(0, new ComponentName((Context) this, (Class<?>) SendingDataSchedulerService.class)).setPeriodic(900000L).setRequiredNetworkType(1).build());
        } else if (Build.VERSION.SDK_INT >= 21) {
            ((JobScheduler) getSystemService("jobscheduler")).schedule(new JobInfo.Builder(0, new ComponentName((Context) this, (Class<?>) SendingDataSchedulerService.class)).setPeriodic(60000L).setRequiredNetworkType(1).build());
        }
    }

    private boolean isMyServiceRunning(Class<?> cls) {
        Iterator<ActivityManager.RunningServiceInfo> it = ((ActivityManager) getSystemService("activity")).getRunningServices(Integer.MAX_VALUE).iterator();
        while (it.hasNext()) {
            if (cls.getName().equals(it.next().service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    protected void onResume() {
        super.onResume();
        NfcAdapter nfcAdapter = this.mNfcAdapter;
        if (nfcAdapter != null && nfcAdapter.isEnabled()) {
            setupForegroundDispatch(this, this, this.mNfcAdapter);
        }
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                startService(new Intent((Context) this, (Class<?>) SendingDataSchedulerService.class));
            } else if (!isMyServiceRunning(this.mSendingService.getClass())) {
                startService(this.mServiceIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (MyApplication.isAppOpenFromMemory()) {
                    String charSequence = HarvestActivity.this.datePicker.getText().toString();
                    if (charSequence.equals(HarvestActivity.this.getCurrentDate())) {
                        return;
                    }
                    HarvestActivity.this.setCurrentDate();
                    if (!charSequence.isEmpty()) {
                        HarvestActivity.this.showDialog();
                        HarvestActivity.this.new GetHarvestList().execute(charSequence.trim());
                    } else {
                        Log.e("NotFinderData", "Not Finder data run: " + charSequence);
                    }
                }
            }
        }, 1000L);
    }

    public JSONObject getOrganizationCredentials() {
        try {
            return new JSONObject(getSharedPreferences("organizationCredentials", 0).getString("userCredentials", null));
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void clearOrganizationCredentials() {
        SharedPreferences.Editor edit = getSharedPreferences("organizationCredentials", 0).edit();
        edit.clear();
        edit.apply();
    }

    public void setupToolbar() {
        setSupportActionBar(this.toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("");
        this.toolbarTitle.setText(getResources().getString(R.string.harvesttitle));
    }

    public void setupDrawerToggle() {
        new ActionBarDrawerToggle(this, this.drawerLayout, this.toolbar, R.string.open_drawer, R.string.close_drawer).syncState();
    }

    public void updateHarvest() {
        final String[] strArr = {""};
        final JSONObject[] jSONObjectArr = {null};
        final JSONArray[] jSONArrayArr = {null};
        new Thread(new Runnable() {
            @Override
            public final void run() {
                HarvestActivity.this.m19lambda$updateHarvest$5$comufieldstrackingHarvestActivity(jSONObjectArr, strArr, jSONArrayArr);
            }
        }).start();
    }

    void m19lambda$updateHarvest$5$comufieldstrackingHarvestActivity(JSONObject[] jSONObjectArr, String[] strArr, final JSONArray[] jSONArrayArr) {
        try {
            JSONObject jSONObject = new JSONObject(MyApplication.getInstance().getPrefManager().getOrganizationEmployee().getOrganizationInfo());
            jSONObjectArr[0] = jSONObject;
            strArr[0] = jSONObject.getString("_id");
            jSONArrayArr[0] = MyApplication.getInstance().getPrefManager().getHarvestList(strArr[0], getCurrentDate());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        this.workerThread.post(new Runnable() {
            @Override
            public final void run() {
                HarvestActivity.this.m18lambda$updateHarvest$4$comufieldstrackingHarvestActivity(jSONArrayArr);
            }
        });
    }

    void m18lambda$updateHarvest$4$comufieldstrackingHarvestActivity(JSONArray[] jSONArrayArr) {
        JSONArray jSONArray = jSONArrayArr[0];
        if (jSONArray != null) {
            try {
                this.harvestIds.clear();
                if (jSONArray.length() != 0) {
                    for (int i = 0; i < jSONArray.length(); i++) {
                        this.harvestIds.add(jSONArray.getJSONObject(i).getString("_id").trim());
                    }
                }
                updateActivity();
            } catch (JSONException unused) {
                showSnackBar(getResources().getString(R.string.somethingwentwrong));
            }
        }
    }

    public void updateActivity() {
        String str;
        HarvestActivity harvestActivity;
        String str2;
        String str3;
        String str4;
        String str5;
        int i;
        HarvestActivity harvestActivity2;
        String str6;
        String str7;
        String str8;
        Date date;
        String str9;
        String str10;
        String str11;
        String str12;
        HarvestActivity harvestActivity3 = this;
        String str13 = "endTime";
        String str14 = "startTime";
        HarvestActivity harvestActivity4 = DublinCoreProperties.DATE;
        String str15 = "fieldDetail";
        String str16 = "subFieldDetail";
        String str17 = "";
        try {
            str = new JSONObject(MyApplication.getInstance().getPrefManager().getOrganizationEmployee().getOrganizationInfo()).getString("_id");
        } catch (JSONException e) {
            e.printStackTrace();
            str = "";
        }
        harvestActivity3.arrayListHarvest.clear();
        try {
            String str18 = " ";
            try {
                if (harvestActivity3.harvestIds.size() != 0) {
                    harvestActivity3.noHarvestEmptyTV.setVisibility(8);
                    int i2 = 0;
                    String str19 = harvestActivity4;
                    while (i2 < harvestActivity3.harvestIds.size()) {
                        String str20 = harvestActivity3.harvestIds.get(i2);
                        String str21 = str17;
                        if (MyApplication.getInstance().getPrefManager().getHarvest(str, str20) != null) {
                            JSONObject harvest = MyApplication.getInstance().getPrefManager().getHarvest(str, str20);
                            i = i2;
                            HarvestDataModel harvestDataModel = new HarvestDataModel();
                            harvestDataModel.setOrganizationId(str);
                            harvestDataModel.setHarvestId(harvest.getString("_id"));
                            str4 = str;
                            try {
                                String str22 = str18;
                                String str23 = str13;
                                MyApplication.getInstance().getPrefManager().storeHarvestTrackingDetail(harvestDataModel.getHarvestId(), getCurrentDate(), new GsonBuilder().disableHtmlEscaping().create().toJson(JsonParser.parseString(String.valueOf(harvest.getJSONArray("scans")))));
                                ArrayList<HarvestPackageModel> arrayList = new ArrayList<>();
                                harvestDataModel.setHarvestLot(harvest.getString("harvestLot"));
                                try {
                                    date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(harvest.getString(str19));
                                } catch (ParseException e2) {
                                    e2.printStackTrace();
                                    date = null;
                                }
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(date);
                                harvestDataModel.setDate(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                                harvestDataModel.setNotes(harvest.getString("notes"));
                                if (!harvest.isNull(str16)) {
                                    harvestDataModel.setFieldType("subField");
                                    harvestDataModel.setFiledId(harvest.getJSONObject(str16).getString("_id"));
                                    str9 = harvest.getJSONObject(str16).getString("name");
                                } else if (harvest.isNull(str15)) {
                                    str9 = str21;
                                } else {
                                    harvestDataModel.setFieldType("field");
                                    harvestDataModel.setFiledId(harvest.getJSONObject(str15).getString("_id"));
                                    str9 = harvest.getJSONObject(str15).getString("name");
                                }
                                str2 = str15;
                                if (harvest.has("cropDetail")) {
                                    str3 = str16;
                                    str10 = str14;
                                    str11 = str19;
                                    if (harvest.has("cultivarDetail")) {
                                        harvestDataModel.setCropId(harvest.getJSONObject("cropDetail").getString("_id"));
                                        if (harvest.getJSONObject("cropDetail").has("defaultPackage")) {
                                            harvestDataModel.setDefaultPackageId(harvest.getJSONObject("cropDetail").getString("defaultPackage"));
                                        }
                                        harvestDataModel.setCultivarId(harvest.getJSONObject("cultivarDetail").getString("_id"));
                                        harvestDataModel.setFieldName(str9 + " (" + harvest.getJSONObject("cropDetail").getString("name") + "/" + harvest.getJSONObject("cultivarDetail").getString("name") + ")");
                                    } else {
                                        harvestDataModel.setDefaultPackageId(harvest.getJSONObject("cropDetail").getString("defaultPackage"));
                                        harvestDataModel.setCropId(harvest.getJSONObject("cropDetail").getString("_id"));
                                        harvestDataModel.setFieldName(str9 + " (" + harvest.getJSONObject("cropDetail").getString("name") + ")");
                                    }
                                    if (harvest.has("packages")) {
                                        JSONArray jSONArray = harvest.getJSONArray("packages");
                                        for (int i3 = 0; i3 <= jSONArray.length() - 1; i3++) {
                                            JSONObject jSONObject = jSONArray.getJSONObject(i3);
                                            HarvestPackageModel harvestPackageModel = new HarvestPackageModel();
                                            harvestPackageModel.setName(jSONObject.getString("name"));
                                            harvestPackageModel.setQuantity(String.valueOf(jSONObject.getInt("totalPackages")));
                                            arrayList.add(harvestPackageModel);
                                        }
                                    }
                                    harvestDataModel.setHarvestPackageModelArray(arrayList);
                                    MyApplication.getInstance().getPrefManager().storeCropPackage(harvest.getJSONObject("cropDetail").getString("_id"), harvest.getJSONObject("cropDetail").getJSONArray("packages").toString());
                                } else {
                                    str10 = str14;
                                    str11 = str19;
                                    str3 = str16;
                                }
                                if (harvest.has("employees")) {
                                    if ((harvest.get("employees") instanceof JSONArray) && harvest.getJSONArray("employees").length() != 0) {
                                        DecimalFormat decimalFormat = new DecimalFormat(".##");
                                        harvestDataModel.setEmployeeCount_Average(harvest.getJSONArray("employees").length() + " EMPLOYEES - ");
                                        if (harvest.has("avgUnits") && !harvest.isNull("avgUnits")) {
                                            StringBuilder sb = new StringBuilder();
                                            sb.append(harvestDataModel.getEmployeeCount_Average());
                                            str12 = "name";
                                            sb.append(decimalFormat.format(harvest.getDouble("avgUnits")));
                                            sb.append(" AVG");
                                            harvestDataModel.setEmployeeCount_Average(sb.toString());
                                        } else {
                                            str12 = "name";
                                            harvestDataModel.setEmployeeCount_Average(harvestDataModel.getEmployeeCount_Average() + "0 AVG");
                                        }
                                    } else {
                                        str12 = "name";
                                        harvestDataModel.setHarvestQuantity(getResources().getString(R.string.notrackingprogress));
                                    }
                                } else {
                                    str12 = "name";
                                    harvestDataModel.setHarvestQuantity(getResources().getString(R.string.notrackingprogress));
                                }
                                if (harvest.has("packages") && harvest.getJSONArray("packages").length() != 0) {
                                    JSONArray jSONArray2 = harvest.getJSONArray("packages");
                                    for (int i4 = 0; i4 < jSONArray2.length(); i4++) {
                                        if (i4 == 0) {
                                            harvestDataModel.setHarvestQuantity(jSONArray2.getJSONObject(i4).getInt("totalPackages") + " X " + jSONArray2.getJSONObject(i4).getString(str12));
                                        } else {
                                            harvestDataModel.setHarvestQuantity(harvestDataModel.getHarvestQuantity() + " + " + jSONArray2.getJSONObject(i4).getInt("totalPackages") + " X " + jSONArray2.getJSONObject(i4).getString(str12));
                                        }
                                    }
                                    str6 = str11;
                                    if (harvest.getString(str6).split("T")[0].equalsIgnoreCase(getCurrentDate())) {
                                        harvestDataModel.setDate(getResources().getString(R.string.today));
                                    }
                                    str8 = str10;
                                    if (harvest.has(str8)) {
                                        str7 = str23;
                                        if (harvest.has(str7)) {
                                            String[] split = harvest.getString(str8).split(":");
                                            String[] split2 = harvest.getString(str7).split(":");
                                            StringBuilder sb2 = new StringBuilder();
                                            sb2.append(split[0]);
                                            sb2.append("H");
                                            sb2.append(split[1]);
                                            str5 = str22;
                                            sb2.append(str5);
                                            sb2.append(getResources().getString(R.string.to));
                                            sb2.append(str5);
                                            sb2.append(split2[0]);
                                            sb2.append("H");
                                            sb2.append(split2[1]);
                                            harvestDataModel.setDuration(sb2.toString());
                                        } else {
                                            str5 = str22;
                                        }
                                    } else {
                                        str5 = str22;
                                        str7 = str23;
                                    }
                                } else {
                                    str5 = str22;
                                    str7 = str23;
                                    str8 = str10;
                                    str6 = str11;
                                    harvestDataModel.setHarvestQuantity(getResources().getString(R.string.notrackingprogress));
                                }
                                harvestActivity2 = this;
                                harvestActivity2.arrayListHarvest.add(harvestDataModel);
                            } catch (JSONException unused) {
                                harvestActivity4 = this;
                                harvestActivity4.showSnackBar(getResources().getString(R.string.somethingwentwrong));
                                harvestActivity = harvestActivity4;
                                harvestActivity.LvaHarvest.notifyDataSetChanged();
                            }
                        } else {
                            str2 = str15;
                            str3 = str16;
                            str4 = str;
                            str5 = str18;
                            i = i2;
                            String str24 = str19;
                            harvestActivity2 = harvestActivity3;
                            str6 = str24;
                            String str25 = str14;
                            str7 = str13;
                            str8 = str25;
                        }
                        i2 = i + 1;
                        str18 = str5;
                        str17 = str21;
                        str = str4;
                        str15 = str2;
                        str16 = str3;
                        HarvestActivity harvestActivity5 = harvestActivity2;
                        str19 = str6;
                        harvestActivity3 = harvestActivity5;
                        String str26 = str7;
                        str14 = str8;
                        str13 = str26;
                    }
                    harvestActivity = harvestActivity3;
                } else {
                    HarvestActivity harvestActivity6 = harvestActivity3;
                    harvestActivity6.noHarvestEmptyTV.setVisibility(0);
                    harvestActivity6.noHarvestEmptyTV.setText(((Object) getResources().getText(R.string.error_no_harvestAvailable)) + " " + ((Object) harvestActivity6.datePicker.getText()));
                    harvestActivity6.showSnackBar(getResources().getString(R.string.noharvestavailable));
                    harvestActivity = harvestActivity6;
                }
            } catch (JSONException unused2) {
            }
        } catch (JSONException unused3) {
            harvestActivity4 = harvestActivity3;
        }
        harvestActivity.LvaHarvest.notifyDataSetChanged();
    }

    public String getCurrentDate() {
        return new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    }

    protected void onPause() {
        NfcAdapter nfcAdapter = this.mNfcAdapter;
        if (nfcAdapter != null && nfcAdapter.isEnabled()) {
            stopForegroundDispatch(this, this.mNfcAdapter);
        }
        super.onPause();
    }

    protected void onDestroy() {
        if (Build.VERSION.SDK_INT >= 21) {
            stopService(new Intent((Context) this, (Class<?>) SendingDataSchedulerService.class));
        } else {
            stopService(this.mServiceIntent);
        }
        LocalBroadcastManager.getInstance(this).unregisterReceiver(this.updateReceiver);
        super.onDestroy();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.harvestmenu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int itemId = menuItem.getItemId();
        if (itemId == 2131362006) {
            MyApplication.getInstance().setLocale("en");
            this.english.setEnabled(false);
            this.french.setEnabled(true);
            this.spanish.setEnabled(true);
            startActivity(getIntent());
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            finish();
            return true;
        }
        if (itemId == 2131362009) {
            MyApplication.getInstance().setLocale("es");
            this.spanish.setEnabled(false);
            this.english.setEnabled(true);
            this.french.setEnabled(true);
            startActivity(getIntent());
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            finish();
            return true;
        }
        if (itemId == 2131362032) {
            MyApplication.getInstance().setLocale("fr");
            this.french.setEnabled(false);
            this.english.setEnabled(true);
            this.spanish.setEnabled(true);
            startActivity(getIntent());
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        this.french = menu.findItem(R.id.francais);
        this.spanish = menu.findItem(R.id.espanol);
        this.english = menu.findItem(R.id.english);
        if (Locale.getDefault().getLanguage().equalsIgnoreCase("en")) {
            this.english.setEnabled(false);
            this.french.setEnabled(true);
            this.spanish.setEnabled(true);
        } else if (Locale.getDefault().getLanguage().equalsIgnoreCase("fr")) {
            this.french.setEnabled(false);
            this.english.setEnabled(true);
            this.spanish.setEnabled(true);
        } else if (Locale.getDefault().getLanguage().equalsIgnoreCase("es")) {
            this.spanish.setEnabled(false);
            this.english.setEnabled(true);
            this.french.setEnabled(true);
        }
        return true;
    }

    public void showDialog() {
        if (this.pDialog.isShowing()) {
            return;
        }
        this.progressBar.setVisibility(0);
        this.pDialog.show();
    }

    public void hideDialog() {
        if (!this.pDialog.isShowing() || this.pDialog == null) {
            return;
        }
        this.progressBar.setVisibility(4);
        try {
            this.pDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isNetworkAvailable() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) getSystemService("connectivity")).getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public String convertStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        while (true) {
            try {
                try {
                    try {
                        String readLine = bufferedReader.readLine();
                        if (readLine == null) {
                            break;
                        }
                        sb.append(readLine);
                        sb.append('\n');
                    } catch (IOException e) {
                        e.printStackTrace();
                        inputStream.close();
                    }
                } catch (Throwable th) {
                    try {
                        inputStream.close();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                    throw th;
                }
            } catch (IOException e3) {
                e3.printStackTrace();
            }
        }
        inputStream.close();
        return sb.toString();
    }

    @Override
    public void onTagDiscovered(Tag tag) {
        new NdefReaderTask().execute(tag);
    }

    private void datePicker() throws ParseException {
        Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(this.datePicker.getText().toString());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);
        new DatePickerDialog(this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                String valueOf = String.valueOf(i3);
                int i4 = i2 + 1;
                String valueOf2 = String.valueOf(i4);
                if (i4 < 10) {
                    valueOf2 = "0" + valueOf2;
                }
                if (i3 < 10) {
                    valueOf = "0" + i3;
                }
                String str = i + "-" + valueOf2 + "-" + valueOf;
                HarvestActivity.this.datePicker.setText(str);
                HarvestActivity.this.showDialog();
                HarvestActivity.this.new GetHarvestList().execute(str);
            }
        }, calendar.get(1), calendar.get(2), calendar.get(5)).show();
    }

    class DrawerItemClickListener implements AdapterView.OnItemClickListener {
        private DrawerItemClickListener() {
        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
            selectItem(i);
        }

        private void selectItem(int i) {
            if (i == 1) {
                HarvestActivity.this.drawerLayout.closeDrawers();
                return;
            }
            if (i == 2) {
                Intent intent = new Intent(HarvestActivity.this.getApplicationContext(), (Class<?>) AllEmployeesActivity.class);
                intent.putExtra("isQrScannerAvailable", HarvestActivity.this.isQrScannerAvailable);
                HarvestActivity.this.startActivity(intent);
                HarvestActivity.this.finish();
                HarvestActivity.this.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                return;
            }
            if (i != 3) {
                if (i == 4) {
                    HarvestActivity.this.drawerLayout.closeDrawers();
                    if (HarvestActivity.this.drawerItem.get(3).name.equals(HarvestActivity.this.getResources().getString(R.string.scanner))) {
                        HarvestActivity.this.startActivity(new Intent((Context) HarvestActivity.this, (Class<?>) QrCodeScannerActivity.class));
                        return;
                    }
                    return;
                }
                return;
            }
            HarvestActivity.this.drawerLayout.closeDrawers();
            final Dialog dialog = new Dialog(HarvestActivity.this);
            dialog.setCanceledOnTouchOutside(false);
            dialog.requestWindowFeature(1);
            dialog.setContentView(R.layout.fragment_logout);
            dialog.setTitle("");
            TextView textView = (TextView) dialog.findViewById(R.id.donButtonDialog);
            TextView textView2 = (TextView) dialog.findViewById(R.id.cancelButtonDialog);
            final EditText editText = (EditText) dialog.findViewById(R.id.orgCode);
            final EditText editText2 = (EditText) dialog.findViewById(R.id.orgkey);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    HarvestActivity.DrawerItemClickListener.this.m21xdf09600c(editText, editText2, dialog, view);
                }
            });
            textView2.setOnClickListener(new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }

        void m21xdf09600c(EditText editText, EditText editText2, final Dialog dialog, View view) {
            if (editText.getText().toString().trim().isEmpty()) {
                editText.setError("Organization code required");
                return;
            }
            if (!editText2.getText().toString().trim().isEmpty()) {
                JSONObject organizationCredentials = HarvestActivity.this.getOrganizationCredentials();
                try {
                    if (editText.getText().toString().trim().equalsIgnoreCase(organizationCredentials.getString("code")) && editText2.getText().toString().trim().equalsIgnoreCase(organizationCredentials.getString("key"))) {
                        HarvestActivity.this.setMessage.setText(HarvestActivity.this.getResources().getString(R.string.loggingout));
                        dialog.dismiss();
                        HarvestActivity.this.showDialog();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public final void run() {
                                HarvestActivity.DrawerItemClickListener.this.m20x4acaf06d(dialog);
                            }
                        }, 3000L);
                    } else {
                        Toast.makeText(HarvestActivity.this.getApplicationContext(), HarvestActivity.this.getResources().getString(R.string.notloginwiththisaccount), 1).show();
                    }
                    return;
                } catch (JSONException unused) {
                    Toast.makeText(HarvestActivity.this.getApplicationContext(), HarvestActivity.this.getResources().getString(R.string.somethingwentwrong), 1).show();
                    return;
                }
            }
            editText2.setError("Organization key required");
        }

        void m20x4acaf06d(Dialog dialog) {
            dialog.dismiss();
            HarvestActivity.this.hideDialog();
            HarvestActivity harvestActivity = HarvestActivity.this;
            harvestActivity.stopService(harvestActivity.mServiceIntent);
            MyApplication.getInstance().logout();
            HarvestActivity.this.clearOrganizationCredentials();
        }
    }

    private class NdefReaderTask extends AsyncTask<Tag, Void, String> {
        @Override
        public void onPostExecute(String str) {
        }

        private NdefReaderTask() {
        }

        @Override
        public String doInBackground(Tag... tagArr) {
            Ndef ndef = Ndef.get(tagArr[0]);
            if (ndef == null) {
                return null;
            }
            NdefRecord[] records = ndef.getCachedNdefMessage().getRecords();
            int length = records.length;
            for (int i = 0; i < length; i++) {
                NdefRecord ndefRecord = records[i];
                if (ndefRecord.getTnf() == 1 && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                    try {
                        return readText(ndefRecord);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        private String readText(NdefRecord ndefRecord) throws UnsupportedEncodingException {
            byte[] payload = ndefRecord.getPayload();
            byte b = payload[0];
            return new String(payload, (b & 51) + 1, (payload.length - r0) - 1, (b & ByteCompanionObject.MIN_VALUE) == 0 ? XmpWriter.UTF8 : XmpWriter.UTF16);
        }
    }

    public class GetAccessDetail extends AsyncTask<String, Void, String> {
        String organizationId = "";

        public GetAccessDetail() {
        }

        @Override
        protected void onPreExecute() {
            HarvestActivity.this.setMessage.setText(HarvestActivity.this.getResources().getText(R.string.loading));
            HarvestActivity.this.showDialog();
            try {
                this.organizationId = new JSONObject(MyApplication.getInstance().getPrefManager().getOrganizationEmployee().getOrganizationInfo()).getString("_id");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String doInBackground(String... strArr) {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 5000);
            InputStream inputStream = null;
            try {
                HttpResponse execute = defaultHttpClient.execute(new HttpGet(EndPoints.GET_ACCESS + this.organizationId));
                if (execute != null) {
                    inputStream = execute.getEntity().getContent();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e2) {
                e2.printStackTrace();
            } catch (IOException e3) {
                e3.printStackTrace();
            }
            return inputStream != null ? HarvestActivity.this.convertStreamToString(inputStream) : "";
        }

        @Override
        public void onPostExecute(String str) {
            HarvestActivity.this.hideDialog();
            if (!str.equals("")) {
                try {
                    if (Boolean.valueOf(new JSONObject(str).getJSONObject("organizationAccess").getBoolean("traceabilityAccess")).booleanValue()) {
                        MyApplication.getInstance().getPrefManager().storeIsTraceabilityAccess(true);
                        HarvestActivity.this.isQrScannerAvailable = true;
                        HarvestActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public final void run() {
                                HarvestActivity.GetAccessDetail.this.m22xe202d4f3();
                            }
                        });
                    } else {
                        MyApplication.getInstance().getPrefManager().storeIsTraceabilityAccess(false);
                    }
                    HarvestActivity.this.new OrganizationLogin().execute(new String[0]);
                    return;
                } catch (JSONException unused) {
                    HarvestActivity harvestActivity = HarvestActivity.this;
                    harvestActivity.showSnackBar(harvestActivity.getResources().getString(R.string.somethingwentwrong));
                    return;
                }
            }
            HarvestActivity harvestActivity2 = HarvestActivity.this;
            harvestActivity2.showSnackBar(harvestActivity2.getResources().getString(R.string.internetconnectionproblem));
        }

        void m22xe202d4f3() {
            HarvestActivity.this.drawerItem.remove(3);
            HarvestActivity.this.drawerItem.add(3, new MenuDataModel(R.drawable.barcode, HarvestActivity.this.getResources().getString(R.string.scanner)));
            HarvestActivity.this.drawerItem.add(4, new MenuDataModel(R.drawable.version, HarvestActivity.this.getResources().getString(R.string.appversion) + " 2.32"));
            HarvestActivity.this.drawerItemCustomAdapter.notifyDataSetChanged();
        }
    }

    public class AddHarvestDetail extends AsyncTask<String, Void, String> {
        JSONObject body = null;
        List<String> pending;
        PendingTracking pendingTracking;

        public AddHarvestDetail() {
        }

        @Override
        protected void onPreExecute() {
            PendingTracking pendingTracking = MyApplication.getInstance().getPendingTracking();
            this.pendingTracking = pendingTracking;
            this.pending = pendingTracking.getAllTracking();
            if (this.pendingTracking.rowCount() > 0) {
                try {
                    this.body = new JSONObject();
                    JSONArray jSONArray = new JSONArray();
                    for (int i = 0; i < this.pending.size(); i++) {
                        jSONArray.put(new JSONObject(this.pendingTracking.getTracking(this.pending.get(i))));
                    }
                    this.body.put("harvestDetails", jSONArray);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }

        @Override
        public String doInBackground(String... strArr) {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 5000);
            HttpPost httpPost = new HttpPost(EndPoints.ADD_MULTIPLE_HARVEST_DETAIL);
            InputStream inputStream = null;
            try {
                StringEntity stringEntity = new StringEntity(this.body.toString());
                stringEntity.setContentType(new BasicHeader("Content-Type", "application/json"));
                httpPost.setEntity(stringEntity);
                HttpResponse execute = defaultHttpClient.execute(httpPost);
                if (execute != null) {
                    inputStream = execute.getEntity().getContent();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e2) {
                e2.printStackTrace();
            } catch (IOException e3) {
                e3.printStackTrace();
            } catch (Exception e4) {
                e4.printStackTrace();
            }
            return inputStream != null ? HarvestActivity.this.convertStreamToString(inputStream) : "";
        }

        @Override
        public void onPostExecute(String str) {
            String trim = HarvestActivity.this.datePicker.getText().toString().trim();
            if (str.equals("")) {
                if (!HarvestActivity.this.isNetworkAvailable()) {
                    HarvestActivity.this.hideDialog();
                } else {
                    HarvestActivity.this.new GetHarvestList().execute(trim);
                }
                if (Build.VERSION.SDK_INT >= 21) {
                    HarvestActivity.this.scheduleJob();
                    return;
                }
                return;
            }
            try {
                if (new JSONObject(str).getBoolean("success")) {
                    for (int i = 0; i < this.pending.size(); i++) {
                        this.pendingTracking.deleteTracking(this.pending.get(i));
                    }
                    this.pending.clear();
                    this.pending = this.pendingTracking.getAllTracking();
                }
                if (!HarvestActivity.this.isNetworkAvailable()) {
                    HarvestActivity.this.hideDialog();
                } else {
                    HarvestActivity.this.new GetHarvestList().execute(trim);
                }
                if (Build.VERSION.SDK_INT >= 21) {
                    HarvestActivity.this.scheduleJob();
                }
            } catch (JSONException unused) {
                if (!HarvestActivity.this.isNetworkAvailable()) {
                    HarvestActivity.this.hideDialog();
                } else {
                    HarvestActivity.this.new GetHarvestList().execute(trim);
                }
                if (Build.VERSION.SDK_INT >= 21) {
                    HarvestActivity.this.scheduleJob();
                }
            }
        }
    }

    public class GetHarvestList extends AsyncTask<String, Void, String> {
        String organizationId = "";
        String currentDate = "";

        public GetHarvestList() {
        }

        @Override
        protected void onPreExecute() {
            HarvestActivity.this.setMessage.setText(HarvestActivity.this.getResources().getString(R.string.refreshingdata));
            try {
                this.organizationId = new JSONObject(MyApplication.getInstance().getPrefManager().getOrganizationEmployee().getOrganizationInfo()).getString("_id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String doInBackground(String... strArr) {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 5000);
            Log.e("DAtaFinderHarvest", "doInBackground:   https://app.ufields.ca/api/production/harvest?optimised=true&date=" + strArr[0] + "&organizationId=" + this.organizationId);
            HttpGet httpGet = new HttpGet(EndPoints.GET_HARVEST + strArr[0] + "&organizationId=" + this.organizationId);
            httpGet.setHeader("timezone", TimeZone.getDefault().getID());
            InputStream inputStream = null;
            try {
                HttpResponse execute = defaultHttpClient.execute(httpGet);
                if (execute != null) {
                    inputStream = execute.getEntity().getContent();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e2) {
                e2.printStackTrace();
            } catch (IOException e3) {
                e3.printStackTrace();
            }
            return inputStream != null ? HarvestActivity.this.convertStreamToString(inputStream) : "";
        }

        @Override
        public void onPostExecute(String str) {
            HarvestActivity.this.hideDialog();
            if (str.equals("")) {
                HarvestActivity.this.updateHarvest();
                return;
            }
            try {
                JSONArray jSONArray = new JSONObject(str).getJSONObject("data").getJSONArray("harvests");
                JsonElement parseString = JsonParser.parseString(String.valueOf(jSONArray));
                MyApplication.getInstance().getPrefManager().storeHarvestList(this.organizationId, HarvestActivity.this.getCurrentDate(), new Gson().toJson(parseString));
                HarvestActivity.this.harvestIds.clear();
                if (jSONArray.length() != 0) {
                    for (int i = 0; i < jSONArray.length(); i++) {
                        HarvestActivity.this.harvestIds.add(jSONArray.getJSONObject(i).getString("_id").trim());
                        MyApplication.getInstance().getPrefManager().storeHarvest(this.organizationId, jSONArray.getJSONObject(i).getString("_id").trim(), jSONArray.getJSONObject(i).toString());
                    }
                }
                MyApplication.getInstance().getPrefManager().storeSyncDateTime(new SimpleDateFormat("yyyy/MM/dd @ kk:mm").format(Calendar.getInstance().getTime()).replace(":", "h"));
                HarvestActivity.this.updateActivity();
            } catch (JSONException unused) {
                HarvestActivity harvestActivity = HarvestActivity.this;
                harvestActivity.showSnackBar(harvestActivity.getResources().getString(R.string.somethingwentwrong));
            }
        }
    }

    public class OrganizationLogin extends AsyncTask<String, Void, String> {
        String code = "";
        String key = "";

        public OrganizationLogin() {
        }

        @Override
        protected void onPreExecute() {
            HarvestActivity.this.setMessage.setText(HarvestActivity.this.getResources().getString(R.string.refreshingdata));
            HarvestActivity.this.showDialog();
            try {
                this.code = HarvestActivity.this.getOrganizationCredentials().getString("code");
                this.key = HarvestActivity.this.getOrganizationCredentials().getString("key");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String doInBackground(String... strArr) {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 5000);
            JSONObject jSONObject = new JSONObject();
            HttpPost httpPost = new HttpPost(EndPoints.ORGANIZATION_LOGIN);
            InputStream inputStream = null;
            try {
                jSONObject.put("code", this.code);
                jSONObject.put("key", this.key);
                StringEntity stringEntity = new StringEntity(jSONObject.toString());
                stringEntity.setContentType(new BasicHeader("Content-Type", "application/json"));
                httpPost.setEntity(stringEntity);
                HttpResponse execute = defaultHttpClient.execute(httpPost);
                if (execute != null) {
                    inputStream = execute.getEntity().getContent();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e2) {
                e2.printStackTrace();
            } catch (IOException e3) {
                e3.printStackTrace();
            } catch (JSONException e4) {
                e4.printStackTrace();
            }
            return inputStream != null ? HarvestActivity.this.convertStreamToString(inputStream) : "";
        }

        @Override
        public void onPostExecute(String str) {
            if (str.equals("")) {
                HarvestActivity.this.hideDialog();
                HarvestActivity.this.updateHarvest();
                return;
            }
            try {
                JSONObject jSONObject = new JSONObject(str);
                if (jSONObject.has("code") && jSONObject.has("message")) {
                    HarvestActivity.this.setMessage.setText(HarvestActivity.this.getResources().getString(R.string.loggingout));
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public final void run() {
                            HarvestActivity.OrganizationLogin.this.m23x26bd339e();
                        }
                    }, 3000L);
                } else {
                    JSONObject jSONObject2 = jSONObject.getJSONObject("organization");
                    MyApplication.getInstance().getPrefManager().storeOrganizationEmployee(new OrganizationEmployee(jSONObject2.toString()));
                    MyApplication.getInstance().getPrefManager().storeEmployees(jSONObject2.getString("_id"), jSONObject.getJSONArray("employees").toString());
                    MyApplication.getInstance().getPrefManager().storeFieldList(jSONObject2.getString("_id"), jSONObject.getJSONArray("fields").toString());
                    if (!HarvestActivity.this.isNetworkAvailable()) {
                        HarvestActivity.this.hideDialog();
                        HarvestActivity.this.updateHarvest();
                        if (Build.VERSION.SDK_INT >= 21) {
                            HarvestActivity.this.scheduleJob();
                        }
                    } else {
                        HarvestActivity.this.new AddHarvestDetail().execute(new String[0]);
                    }
                }
            } catch (JSONException unused) {
                if (!HarvestActivity.this.isNetworkAvailable()) {
                    HarvestActivity.this.hideDialog();
                    HarvestActivity.this.updateHarvest();
                } else {
                    HarvestActivity.this.new AddHarvestDetail().execute(new String[0]);
                }
            }
        }

        void m23x26bd339e() {
            HarvestActivity.this.hideDialog();
            MyApplication.getInstance().logout();
            HarvestActivity.this.clearOrganizationCredentials();
        }
    }

    private class UpdateReceiver extends BroadcastReceiver {
        private UpdateReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.hasExtra("dataUpdated") && intent.getBooleanExtra("dataUpdated", false)) {
                HarvestActivity.this.updateHarvest();
            }
        }
    }
}