package cpm.com.gskmtorange.dailyentry;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
//import com.crashlytics.android.Crashlytics;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import com.androidbuts.multispinnerfilter.KeyPairBoolData;
import com.androidbuts.multispinnerfilter.MultiSpinnerSearch;
import com.androidbuts.multispinnerfilter.SpinnerListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

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

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.CoachingVisitGetterSetter;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.SupervisorListGetterSetter;

public class CoachingVisitActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
    private Context context;
    private GSKOrangeDB database;
    ArrayList<SupervisorListGetterSetter> supervisorList;
    private Spinner exist_spinner; //supervisor_spinner;
    private ArrayAdapter<CharSequence> exist_adapter, supervisor_adapter;
    int coaching_visit;
    LinearLayout linear_supervisor;
    ImageView img_cam;
    FloatingActionButton fab_next, fab_save;
    String emp_id;
    protected String _pathforcheck = "", _path, image_name = "", str, country_id, store_flag_str;
    String visit_date, store_id, username;
    private SharedPreferences preferences;
    String gallery_package = "";
    Uri outputFileUri;
    boolean saved_flag = false, update_flag = false;
    ArrayList<CoachingVisitGetterSetter> coachingVisitdata;
    boolean coaching_visit_camera_flag = false;
    MultiSpinnerSearch multi_spinner_supervisor;
    ArrayList<String> selectedSupervisorList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coaching_visit);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        linear_supervisor = (LinearLayout) findViewById(R.id.linear_supervisor);
        exist_spinner = (Spinner) findViewById(R.id.spinner_coaching_visit);
        //supervisor_spinner = (Spinner) findViewById(R.id.spinner_supervisor);
        img_cam = (ImageView) findViewById(R.id.img_cam);

        multi_spinner_supervisor = (MultiSpinnerSearch) findViewById(R.id.multi_spinner_supervisor);
        context = this;

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));

        toolbar.setTitle(getResources().getString(R.string.title_activity_coaching_visit));

        str = CommonString.getImagesFolder(context);

        store_id = getIntent().getStringExtra(CommonString.KEY_STORE_ID);
        store_flag_str = getIntent().getStringExtra(CommonString.KEY_STORE_FLAG);

        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        //store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, null);

        fab_next = (FloatingActionButton) findViewById(R.id.fab);
        fab_save = (FloatingActionButton) findViewById(R.id.fab_save);

        database = new GSKOrangeDB(this);
        database.open();

        coachingVisitdata = database.getCoachingVisitData(store_id);

        //Enable disable According to Configuration
        ArrayList<ConfigurationMasterGetterSetter> configurationData = database.getConfigurationMasterData(country_id);
        if (configurationData.size() > 0) {

            for (int i = 0; i < configurationData.size(); i++) {
                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("COACHING VISIT IMAGE") && configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    coaching_visit_camera_flag = true;
                    break;
                }
            }
        }

        if (coaching_visit_camera_flag) {
            img_cam.setVisibility(View.VISIBLE);
        } else {
            img_cam.setVisibility(View.GONE);
        }


        supervisorList = database.getSupervisorListData();

        exist_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);

        String select_str = getResources().getString(R.string.select);

        exist_adapter.add(select_str);
        exist_adapter.add(getResources().getString(R.string.yes));
        exist_adapter.add(getResources().getString(R.string.no));

        exist_spinner.setAdapter(exist_adapter);

        exist_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        exist_spinner.setOnItemSelectedListener(this);

        if (coachingVisitdata.size() != 0) {
            update_flag = true;
            fab_save.hide();//setVisibility(View.GONE);
            fab_next.show();//setVisibility(View.VISIBLE);
            if (coachingVisitdata.get(0).isExists()) {
                exist_spinner.setSelection(1);
            } else {
                exist_spinner.setSelection(2);
            }
            exist_spinner.setEnabled(false);
        }

        fab_next.setOnClickListener(this);
        fab_save.setOnClickListener(this);
        img_cam.setOnClickListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        if (parent.getId() == R.id.spinner_coaching_visit) {

            if (position != 0) {

                if (!update_flag) {

                    fab_save.show(); //setVisibility(View.VISIBLE);

                    if (position == 1) {

                        linear_supervisor.setVisibility(View.VISIBLE);
                        coaching_visit = 1;

                        final List<KeyPairBoolData> listArray0 = new ArrayList<>();

                        for (int i = 0; i < supervisorList.size(); i++) {
                            KeyPairBoolData h = new KeyPairBoolData();
                            h.setId(i + 1);
                            h.setName(supervisorList.get(i).getSUPERVISOR().get(0));
                            h.setSelected(false);
                            listArray0.add(h);
                        }

                        multi_spinner_supervisor.setItems(listArray0, -1, new SpinnerListener() {
                            @Override
                            public void onItemsSelected(List<KeyPairBoolData> items) {

                                selectedSupervisorList.clear();

                                for (int i = 0; i < items.size(); i++) {
                                    if (items.get(i).isSelected()) {
                                        selectedSupervisorList.add(items.get(i).getName());
                                        Log.i("MultiSpinner", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
                                    }
                                }
                            }
                        });

                    } else {
                        coaching_visit = 0;
                        selectedSupervisorList.clear();
                        linear_supervisor.setVisibility(View.GONE);
                    }
                }

            } else {
                coaching_visit = -1;
                linear_supervisor.setVisibility(View.GONE);
                fab_save.hide(); //setVisibility(View.GONE);
            }

        } else if (parent.getId() == R.id.multi_spinner_supervisor) {
            // Commented-out code from original
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.img_cam) {

            _pathforcheck = store_id + "CoachingVisit" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            startCameraActivity();

        } else if (v.getId() == R.id.fab_save) {

            if (coaching_visit == 1) {
                String error_msg = "";
                boolean flag = true;

                if (selectedSupervisorList.size() == 0) {
                    flag = false;
                    error_msg = getString(R.string.title_activity_select_dropdown);
                } else if (coaching_visit_camera_flag && image_name.equals("")) {
                    flag = false;
                    error_msg = getString(R.string.clickimage);
                }

                if (flag) {
                    for (int i = 0; i < selectedSupervisorList.size(); i++) {
                        CoachingVisitGetterSetter coachingVisitGetterSetter = new CoachingVisitGetterSetter();
                        coachingVisitGetterSetter.setEmp_id(getEmp_idFromName(selectedSupervisorList.get(i)));
                        coachingVisitGetterSetter.setImg_path(image_name);
                        coachingVisitGetterSetter.setExists(coaching_visit == 1);
                        database.insertCoachingVisitData(coachingVisitGetterSetter, store_id);
                    }

                    Toast.makeText(context, getString(R.string.save_message), Toast.LENGTH_SHORT).show();
                    saved_flag = true;
                    fab_next.show(); // setVisibility(View.VISIBLE);
                } else {
                    Snackbar.make(linear_supervisor, error_msg, Snackbar.LENGTH_SHORT).show();
                }

            } else {
                CoachingVisitGetterSetter coachingVisitGetterSetter = new CoachingVisitGetterSetter();
                coachingVisitGetterSetter.setEmp_id("0");
                coachingVisitGetterSetter.setImg_path(image_name);
                coachingVisitGetterSetter.setExists(coaching_visit == 1);

                database.insertCoachingVisitData(coachingVisitGetterSetter, store_id);

                Toast.makeText(context, getString(R.string.save_message), Toast.LENGTH_SHORT).show();
                saved_flag = true;
                fab_next.show(); // setVisibility(View.VISIBLE);
            }

        } else if (v.getId() == R.id.fab) {
            if (saved_flag || update_flag) {
                Intent i = new Intent(CoachingVisitActivity.this, CoachingVisitStoreActivity.class);
                i.putExtra(CommonString.KEY_STORE_ID, store_id);
                i.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                startActivity(i);
                finish();
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);

            } else {
                Snackbar.make(linear_supervisor, getString(R.string.please_save_data), Snackbar.LENGTH_SHORT).show();
            }
        }

    }

    String getEmp_idFromName(String name) {
        String emp_id = "0";

        for (int i = 0; i < supervisorList.size(); i++) {
            if (supervisorList.get(i).getSUPERVISOR().get(0).equalsIgnoreCase(name)) {
                emp_id = supervisorList.get(i).getEMP_ID().get(0);
                break;
            }
        }

        return emp_id;
    }

    protected void startCameraActivity() {
        try {

            Log.i("MakeMachine", "startCameraActivity()");
            File file = new File(_path);
            outputFileUri = FileProvider.getUriForFile(context, "cpm.com.gskmtorange.fileprovider", file);

            String defaultCameraPackage = "";
            final PackageManager packageManager = getPackageManager();
            List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
            for (int n = 0; n < list.size(); n++) {
                if ((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                    Log.e("TAG", "Installed Applications  : " + list.get(n).loadLabel(packageManager).toString());
                    Log.e("TAG", "package name  : " + list.get(n).packageName);

                    //temp value in case camera is gallery app above jellybean
                    String packag = list.get(n).loadLabel(packageManager).toString();
                    if (packag.equalsIgnoreCase("Gallery") || packag.equalsIgnoreCase("Galeri") || packag.equalsIgnoreCase("الاستوديو")) {
                        gallery_package = list.get(n).packageName;
                    }

                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {
                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    } else {

                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {

                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    }
                }
            }

            //com.android.gallery3d

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(defaultCameraPackage);
            startActivityForResult(intent, 0);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(gallery_package);
            startActivityForResult(intent, 0);

        } catch (Exception e) {
            // Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
            // Crashlytics.logException(e.getCause());
            //Crashlytics.logException(new Exception(e.getCause()));
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingSuperCall")
    @SuppressWarnings("deprecation")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("MakeMachine", "resultCode: " + resultCode);
        switch (resultCode) {
            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;

            case -1:

                if (_pathforcheck != null && !_pathforcheck.equals("")) {
                    if (new File(str + _pathforcheck).exists()) {

                        img_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_green));

                        image_name = _pathforcheck;

                        _pathforcheck = "";

                    }
                }

                break;
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }

        return super.onOptionsItemSelected(item);
    }
}
