package cpm.com.gskmtorange;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

//import com.crashlytics.android.Crashlytics;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;
import java.util.ArrayList;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GeoTag.GeoTagStoreList;
import cpm.com.gskmtorange.GetterSetter.CoverageBean;
import cpm.com.gskmtorange.GetterSetter.StoreBean;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.dailyentry.CounterfeitIndicatorWebActivity;
import cpm.com.gskmtorange.dailyentry.DeliveryCallActivity;
import cpm.com.gskmtorange.dailyentry.FutureJCPActivity;
import cpm.com.gskmtorange.dailyentry.PlanogramPDFActivity;
import cpm.com.gskmtorange.dailyentry.ServiceActivity;
import cpm.com.gskmtorange.dailyentry.SettingsActivity;
import cpm.com.gskmtorange.dailyentry.StoreListActivity;
import cpm.com.gskmtorange.download.DownloadActivity;
import cpm.com.gskmtorange.password.ChangePasswordActivity;
import cpm.com.gskmtorange.pharma_stores.PharmaActivity;
import cpm.com.gskmtorange.pharma_stores.PharmaActivityFragment;
import cpm.com.gskmtorange.upload.PreviousDataUploadActivity;
import cpm.com.gskmtorange.upload.UploadActivity;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationMasterGetterSetter;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private Context context;
    WebView webView;
    ImageView imageView;
    String date;
    private SharedPreferences preferences = null;
    GSKOrangeDB db;
    String user_name, country_id;
    ArrayList<StoreBean> storelist = new ArrayList<StoreBean>();
    View headerView;
    ArrayList<CoverageBean> coverageList;
    String error_msg;
    Toolbar toolbar;
    NavigationView navigationView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        context = this;
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        date = preferences.getString(CommonString.KEY_DATE, null);
        imageView = (ImageView) findViewById(R.id.img_main);
        webView = (WebView) findViewById(R.id.webview);
        String url = preferences.getString(CommonString.KEY_NOTICE_BOARD_LINK, "");
        user_name = preferences.getString(CommonString.KEY_USERNAME, null);
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, null);
        db = new GSKOrangeDB(MainActivity.this);
        webView.setWebViewClient(new MyWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        if (!url.isEmpty()) {
            webView.loadUrl(url);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        headerView = LayoutInflater.from(this).inflate(R.layout.nav_header_main, navigationView, false);
        TextView tv_username = (TextView) headerView.findViewById(R.id.nav_user_name);
        //tv_usertype = (TextView) headerView.findViewById(R.id.nav_user_type);
        ImageView img_change_password = (ImageView) headerView.findViewById(R.id.img_change_password);
        tv_username.setText(user_name);
        //tv_usertype.setText(user_type);

        img_change_password.setOnClickListener(v -> {
            Intent in = new Intent(context, ChangePasswordActivity.class);
            startActivity(in);
        });

        navigationView.addHeaderView(headerView);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        toolbar.setTitle(getString(R.string.main_menu_activity_name));
        db.open();
        //usk
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        // get menu from navigationView
        Menu menu = navigationView.getMenu();
        // find MenuItem you want to change
        MenuItem nav_route_plan = menu.findItem(R.id.nav_route_plan);
        nav_route_plan.setTitle(getResources().getString(R.string.menu_daily_route_plan));
        MenuItem nav_route_plan1 = menu.findItem(R.id.nav_download);
        nav_route_plan1.setTitle(getResources().getString(R.string.menu_daily_download));
        MenuItem nav_route_plan2 = menu.findItem(R.id.nav_upload);
        nav_route_plan2.setTitle(getResources().getString(R.string.menu_upload_data));
        MenuItem nav_route_plan3 = menu.findItem(R.id.nav_geotag);
        nav_route_plan3.setTitle(getResources().getString(R.string.menu_geotag));
        MenuItem nav_route_plan4 = menu.findItem(R.id.nav_deviation);
        nav_route_plan4.setTitle(getResources().getString(R.string.menu_deviation_data));
        MenuItem nav_route_plan5 = menu.findItem(R.id.nav_delivery_call);
        nav_route_plan5.setTitle(getResources().getString(R.string.delivery_call));
        MenuItem nav_route_plan6 = menu.findItem(R.id.nav_future_jcp);
        nav_route_plan6.setTitle(getResources().getString(R.string.future_route_plan));
        MenuItem nav_route_plan7 = menu.findItem(R.id.nav_planogram);
        nav_route_plan7.setTitle(getResources().getString(R.string.category_performance_PLANOGRAM));
        MenuItem nav_route_plan8 = menu.findItem(R.id.nav_pharmacy_stores);
        nav_route_plan8.setTitle(getResources().getString(R.string.pharma_stores));
        MenuItem nav_route_plan9 = menu.findItem(R.id.nav_additional_stores);
        nav_route_plan9.setTitle(getResources().getString(R.string.additional_stores));
        MenuItem nav_route_plan10 = menu.findItem(R.id.nav_additional_adhoc_stores);
        nav_route_plan10.setTitle(getResources().getString(R.string.additional_adhoc_stores));
        MenuItem nav_route_plan11 = menu.findItem(R.id.nav_counterfeit_indicator);
        nav_route_plan11.setTitle(getResources().getString(R.string.title_activity_counterfeit_indicator_web));
        MenuItem nav_route_plan12 = menu.findItem(R.id.nav_exit);
        nav_route_plan12.setTitle(getResources().getString(R.string.menu_exit));
        MenuItem nav_route_plan13 = menu.findItem(R.id.nav_setting);
        nav_route_plan13.setTitle(getResources().getString(R.string.menu_setting));
        MenuItem nav_route_plan14 = menu.findItem(R.id.nav_services);
        nav_route_plan14.setTitle(getResources().getString(R.string.menu_services));
        //Enable disable According to Configuration
        ArrayList<ConfigurationMasterGetterSetter> configurationData = db.getConfigurationMasterData(country_id);
        if (!configurationData.isEmpty()) {
            for (int i = 0; i < configurationData.size(); i++) {
                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("ADHOC REPORTING") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_deviation).setVisible(true);
                }
                //temp remove it
                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("PDF ALLOW") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_planogram).setVisible(true);
                }

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("DELIVERY CALLS") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_delivery_call).setVisible(true);
                }

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("ADDITIONAL STORE") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_additional_stores).setVisible(true);
                }

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("PHARMA STORE") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_pharmacy_stores).setVisible(true);
                }


                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("COUNTERFEIT INDICATORS") &&
                        configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    Menu nav_Menu = navigationView.getMenu();
                    nav_Menu.findItem(R.id.nav_counterfeit_indicator).setVisible(true);
                }

            }
        }

        db.open();
        coverageList = db.getCoverageData(date, null);
        storelist = db.getStoreData(date, CommonString.KEY_JOURNEY_PLAN);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            // super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_route_plan) {
            Intent in_jcp = new Intent(this, StoreListActivity.class);
            in_jcp.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_JCP);
            startActivity(in_jcp);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_download) {
            downloadMethod();
        } else if (id == R.id.nav_upload) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(getResources().getString(R.string.dialog_title));
            builder.setMessage(getResources().getString(R.string.want_to_upload)).setCancelable(false)
                    .setPositiveButton(getResources().getString(R.string.ok), (dialog, id1) -> {
                        db.open();
                        if (checkNetIsAvailable()) {
                            if (db.getSKUMasterData(null).isEmpty()) {
                                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT)
                                        .setAction("Action", null).show();
                            } else {
                                if (coverageList.isEmpty()) {
                                    Snackbar.make(webView, R.string.no_data_for_upload, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                } else {
                                    if (isStoreCheckedIn() && isValid()) {
                                        Intent i = new Intent(getBaseContext(), UploadActivity.class);
                                        startActivity(i);
                                    } else {
                                        Snackbar.make(webView, error_msg, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                    }
                                }
                            }
                        } else {
                            Snackbar.make(webView, getResources().getString(R.string.nonetwork), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                        }
                    }).setNegativeButton(getResources().getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
            AlertDialog alert = builder.create();
            alert.show();

        } else if (id == R.id.nav_geotag) {
            if (!storelist.isEmpty()) {
                Intent startDownload = new Intent(this, GeoTagStoreList.class);
                startActivity(startDownload);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                Snackbar.make(headerView, R.string.title_store_list_download_data, Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }

        } else if (id == R.id.nav_exit) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(getResources().getString(R.string.dialog_title));
            builder.setMessage(getResources().getString(R.string.want_to_exit)).setCancelable(false)
                    .setPositiveButton(getResources().getString(R.string.ok), (dialog, id12) -> {
                        ActivityCompat.finishAffinity(MainActivity.this);
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }).setNegativeButton(getResources().getString(R.string.cancel), (dialog, which) -> {
                        dialog.dismiss();
                    });
            AlertDialog alert = builder.create();
            alert.show();

        } else if (id == R.id.nav_setting) {
            Intent startDownload = new Intent(this, SettingsActivity.class);
            startActivity(startDownload);
            finish();
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_services) {
            Intent startservice = new Intent(this, ServiceActivity.class);
            startActivity(startservice);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_future_jcp) {
            Intent startDownload = new Intent(this, FutureJCPActivity.class);
            startActivity(startDownload);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_planogram) {
            if (checkNetIsAvailable()) {
                Intent planogram_pdf = new Intent(this, PlanogramPDFActivity.class);
                startActivity(planogram_pdf);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                Snackbar.make(webView, getResources().getString(R.string.nonetwork), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            }

        } else if (id == R.id.nav_deviation) {
            db.open();
            if (db.getSKUMasterData(null).isEmpty()) {
                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            } else {
                Intent in = new Intent(this, StoreListActivity.class);
                in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_DEVIATION);
                startActivity(in);
            }
        } else if (id == R.id.nav_delivery_call) {
            Intent in = new Intent(this, DeliveryCallActivity.class);
            startActivity(in);

            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_pharmacy_stores) {
            Intent in = new Intent(this, StoreListActivity.class);
            in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_PHARMA);
            startActivity(in);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        } else if (id == R.id.nav_additional_stores) {
            db.open();
            if (db.getSKUMasterData(null).isEmpty()) {
                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            } else {
                Intent in = new Intent(this, StoreListActivity.class);
                in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_ADDITIONAL);
                startActivity(in);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            }
        } else if (id == R.id.nav_additional_adhoc_stores) {
            db.open();
            if (db.getSKUMasterData(null).isEmpty()) {
                Snackbar.make(webView, R.string.title_store_list_download_data, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            } else {
                Intent in = new Intent(this, StoreListActivity.class);
                in.putExtra(CommonString.KEY_STORE_FLAG, CommonString.FROM_ADDITIONAL_ADHOC);
                startActivity(in);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            }
        } else if (id == R.id.nav_counterfeit_indicator) {
            Intent intent = new Intent(this, CounterfeitIndicatorWebActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            imageView.setVisibility(View.INVISIBLE);
            webView.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
            view.clearCache(true);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

    }

    public boolean checkNetIsAvailable() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
        return isConnected;
    }

    public boolean isStoreCheckedIn() {

        boolean result_flag = true;
        for (int i = 0; i < coverageList.size(); i++) {

            String status = coverageList.get(i).getStatus();
            if (status.equals(CommonString.KEY_INVALID) || status.equals(CommonString.KEY_VALID)) {
                result_flag = false;
                error_msg = getResources().getString(R.string.title_store_list_checkout_current);
                break;
            }
        }

        return result_flag;
    }

    public boolean isValid() {
        boolean flag = false;
        String storestatus = "";
        for (int i = 0; i < coverageList.size(); i++) {

            StoreBean store_data = db.getSpecificStoreData(date, coverageList.get(i).getStoreId(), coverageList.get(i).getFlag_from());

            storestatus = store_data.getUPLOAD_STATUS();
            String coverage_status = store_data.getCHECKOUT_STATUS();

            if (!storestatus.equalsIgnoreCase(CommonString.KEY_U) && !storestatus.equalsIgnoreCase(CommonString.KEY_UN)) {
                if ((coverage_status.equalsIgnoreCase(CommonString.KEY_Y) || storestatus.equalsIgnoreCase(CommonString.KEY_P) ||
                        storestatus.equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE))) {
                    flag = true;
                    break;

                }
            }
        }

        if (!flag)
            error_msg = getResources().getString(R.string.no_data_for_upload);

        return flag;
    }

    public boolean isPreviousValid(String visit_date) {
        boolean isvalid = false;
        ArrayList<CoverageBean> coverage_list = db.getPreviousCoverageData(visit_date, null);
        for (int i = 0; i < coverage_list.size(); i++) {
            StoreBean storeData = db.getSpecificStoreData(coverage_list.get(i).getVisitDate(), coverage_list.get(i).getStoreId(), coverage_list.get(i).getFlag_from());
            if (storeData.getSTORE_ID() != null) {

                if (!storeData.getUPLOAD_STATUS().equals(CommonString.KEY_U) && !storeData.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_UN) && (storeData.getCHECKOUT_STATUS().equals(CommonString.KEY_Y) ||
                        storeData.getCHECKOUT_STATUS().equals(CommonString.KEY_L) || storeData.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_P))) {
                    isvalid = true;
                    break;
                }
            }
        }
        return isvalid;
    }

    //for download
    public void downloadMethod() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(getResources().getString(R.string.dialog_title));
        builder.setMessage(getResources().getString(R.string.want_to_download)).setCancelable(false)
                .setPositiveButton(getResources().getString(R.string.ok), (dialog, id) -> {
                    if (checkNetIsAvailable()) {
                        boolean previousflag = false;
                        if (db.isPreviousCoverageDataFilled(date)) {
                            if (isPreviousValid(date)) {
                                previousflag = true;
                            } else {
                                db.deletePreviousCoverageData(date);
                            }
                        }

                        if (previousflag) {
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                            builder1.setTitle("Parinaam");
                            builder1.setMessage(getResources().getString(R.string.previous_data_upload)).setCancelable(false)
                                    .setPositiveButton(getResources().getString(R.string.ok), (dialog1, id1) -> {
                                        Intent in = new Intent(context, PreviousDataUploadActivity.class);
                                        startActivity(in);
                                        //finish();
                                    });
                            AlertDialog alert = builder1.create();
                            alert.show();

                        } else {
                            Intent in = new Intent(context, DownloadActivity.class);
                            startActivity(in);
                        }
                    } else {
                        Snackbar.make(webView, getResources().getString(R.string.nonetwork), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                    }
                }).setNegativeButton(getResources().getString(R.string.cancel), (dialog, which) -> {
                    dialog.dismiss();
                });
        AlertDialog alert = builder.create();
        alert.show();


    }
}
