package de.jg_cody.Teraplex.ui.settings;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.util.Locale;
import java.util.Objects;

import de.jg_cody.Teraplex.IntroActivity;
import de.jg_cody.Teraplex.MainActivity;
import de.jg_cody.Teraplex.R;

import static android.content.Context.MODE_PRIVATE;

public class SettingsFragment extends Fragment {

    private EditText editExportFile_name;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_settings, container, false);
        SharedPreferences p = requireContext().getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        String Background = p.getString("Background", null);
        if (Background != null) {
            ImageView I = root.findViewById(R.id.Background);
            byte[] BA = Base64.decode(Background, Base64.DEFAULT);
            I.setImageDrawable(new BitmapDrawable(getResources(), MainActivity.scaleCenterCrop(BitmapFactory.decodeByteArray(BA, 0, BA.length), MainActivity.getScreenHeight(), MainActivity.getScreenWidth())));
            I.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }
        Button Language = root.findViewById(R.id.button_language);
        Language.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                showChangeLanguageDialog();

            }
        });
        Button Export = root.findViewById(R.id.button_export);
        Export.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                createFile();
            }
        });
        Button Import = root.findViewById(R.id.button_import);
        Import.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                //showImportDialog();
                openFile();
            }
        });
        Button Reset = root.findViewById(R.id.button_reset);
        Reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }

                AlertDialog mDialog = new AlertDialog.Builder(getContext())
                        .setTitle(R.string.reset_app)
                        .setMessage(R.string.are_you_sure_to_reset)

                        // Specifying a listener allows you to take an action before dismissing the dialog.
                        // The dialog is automatically dismissed when a dialog button is clicked.
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (MainActivity.button_vibration) {
                                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                                    assert vr != null;
                                    vr.vibrate(100);
                                }
                                try {
                                    requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE).edit().clear().apply();
                                    startActivity(requireActivity().getIntent());
                                    requireActivity().finish();
                                } catch (Exception ignored) {
                                }

                                // Continue with delete operation
                            }
                        })

                        // A null listener allows the button to dismiss the dialog and take no further action.
                        .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (MainActivity.button_vibration) {
                                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                                    assert vr != null;
                                    vr.vibrate(100);
                                }
                            }
                        }).create();
                Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawableResource(R.drawable.button_round);
                mDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
                mDialog.show();
            }

        });
        Button choose_background = root.findViewById(R.id.button_pickimage);
        choose_background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                showChangeBackgroundDialog();


            }
        });
        Button theme1 = root.findViewById(R.id.button_theme_red_blue);
        theme1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putString("Theme", "RED_BLUE");
                editor.apply();
                startActivity(requireActivity().getIntent());
                requireActivity().finish();


            }
        });
        Button theme2 = root.findViewById(R.id.button_theme_green_yellow);
        theme2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putString("Theme", "GREEN_YELLOW");
                editor.apply();
                startActivity(requireActivity().getIntent());
                requireActivity().finish();


            }
        });
        Button theme3 = root.findViewById(R.id.button_theme_orange_turquoise);
        theme3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putString("Theme", "ORANGE_TURQUOISE");
                editor.apply();
                startActivity(requireActivity().getIntent());
                requireActivity().finish();


            }
        });
        Button theme4 = root.findViewById(R.id.button_theme_yellow_blue);
        theme4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putString("Theme", "YELLOW_BLUE");
                editor.apply();
                startActivity(requireActivity().getIntent());
                requireActivity().finish();


            }
        });
        Button theme5 = root.findViewById(R.id.button_theme_pink_green);
        theme5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putString("Theme", "PINK_GREEN");
                editor.apply();
                startActivity(requireActivity().getIntent());
                requireActivity().finish();


            }
        });
        ((Switch) root.findViewById(R.id.buttonvibration_switch)).setChecked(MainActivity.button_vibration);
        ((Switch) root.findViewById(R.id.buttonvibration_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                MainActivity.button_vibration = isChecked;
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putBoolean("Vibration", MainActivity.button_vibration);
                editor.apply();
            }
        });
        ((Switch) root.findViewById(R.id.animation_switch)).setChecked(IntroActivity.show_logoanimation);
        ((Switch) root.findViewById(R.id.animation_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                IntroActivity.show_logoanimation = isChecked;
                SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
                editor.putBoolean("Logoanimation", IntroActivity.show_logoanimation);
                editor.apply();
            }
        });
        return root;
    }

    private void showChangeLanguageDialog() {
        final String[] listItems = {"GERMAN", "ENGLISCH"};
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
        mBuilder.setTitle(getString(R.string.choose_language));
        mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                if (i == 0) {
                    setLocale("de");
                    startActivity(requireActivity().getIntent());
                    requireActivity().finish();
                } else if (i == 1) {
                    setLocale("en");
                    startActivity(requireActivity().getIntent());
                    requireActivity().finish();
                }
                dialogInterface.dismiss();
            }
        });
        AlertDialog mDialog = mBuilder.create();
        Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawableResource(R.drawable.button_round);
        mDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
        mDialog.show();
    }

    private void showChangeBackgroundDialog() {
        final String[] listItems = {getString(R.string.image), getString(R.string.reset_background)};
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
        mBuilder.setTitle(getString(R.string.choose_backgroundtype));
        mBuilder.setSingleChoiceItems(listItems, -5, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                if (i == 0) {
                    Intent a = new Intent(
                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    requireActivity().startActivityForResult(a, MainActivity.RESULT_LOAD_IMAGE);
                } else if (i == 1) {
                    requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE).edit().remove("Background").apply();
                    startActivity(requireActivity().getIntent());
                    requireActivity().finish();

                }
                dialogInterface.dismiss();
            }
        });
        AlertDialog mDialog = mBuilder.create();
        Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawableResource(R.drawable.button_round);
        mDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
        mDialog.show();
    }

    private void setLocale(String lang) {
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        requireContext().getResources().updateConfiguration(config, requireContext().getResources().getDisplayMetrics());
        SharedPreferences.Editor editor = requireContext().getSharedPreferences("appsettings", MODE_PRIVATE).edit();
        editor.putString("Language", lang);
        editor.apply();
    }

    private void showImportDialog() {
        Intent a = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        requireActivity().startActivityForResult(a, MainActivity.RESULT_LOAD_IMAGE);
    }


    private void createFile() {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/json");
        intent.putExtra(Intent.EXTRA_TITLE, "export.json");

        // Optionally, specify a URI for the directory that should be opened in
        // the system file picker when your app creates the document.
        //intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);

        requireActivity().startActivityForResult(intent, 1);
    }
    private void openFile() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/*");

        // Optionally, specify a URI for the file that should appear in the
        // system file picker when it loads.


        requireActivity().startActivityForResult(intent, MainActivity.PICK_PDF_FILE);
    }


}