package de.jg_cody.Teraplex;

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.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import de.jg_cody.Teraplex.ui.credits.CreditsFragment;
import de.jg_cody.Teraplex.ui.settings.SettingsFragment;
import de.jg_cody.Teraplex.ui.tabs.TabsFragment;


public class MainActivity extends AppCompatActivity {
    public static int RESULT_LOAD_IMAGE = 0;
    private AppBarConfiguration mAppBarConfiguration;
    // Request code for selecting a PDF document.
    public static final int PICK_PDF_FILE = 2;
    public static final int CREATE_FILE = 1;

    public static boolean editmode = false;
    public static boolean button_vibration = false;

    int lastID = 6969;

    Map<String, MenuItem> tabitems = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        getWindow().setNavigationBarColor(Color.BLUE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            getWindow().setStatusBarContrastEnforced(false);
        }
        //getWindow().setBackgroundDrawableResource(R.drawable.toolbartop);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
        SharedPreferences p = getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        String Language = p.getString("Language", "");
        Locale locale = new Locale(Language);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

        button_vibration = p.getBoolean("Vibration",  false );
        IntroActivity.show_logoanimation = p.getBoolean("Logoanimation",  true );

        String Theme = p.getString("Theme", "RED_BLUE");
        if (Theme.equals("RED_BLUE")) {
            setTheme(R.style.Theme_red_blue);
        }
        if (Theme.equals("GREEN_YELLOW")) {
            setTheme(R.style.Theme_green_yellow);
        }
        if (Theme.equals("ORANGE_TURQUOISE")) {
            setTheme(R.style.Theme_orange_turquoise);
        }
        if (Theme.equals("YELLOW_BLUE")) {
            setTheme(R.style.Theme_yellow_blue);
        }
        if (Theme.equals("PINK_GREEN")) {
            setTheme(R.style.Theme_pink_green);
        }

        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setBackgroundResource(R.drawable.toolbartop);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_settings, R.id.nav_tabs, R.id.nav_über, R.id.nav_terminal)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
        ((Switch) navigationView.getMenu().getItem(2).getActionView().findViewById(R.id.switch_editmode)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (button_vibration) {
                    Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }

                editmode = isChecked;
                Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
                NavHostFragment nhf = (NavHostFragment) currentFragment;
                assert nhf != null;
                Fragment childfragment = nhf.getChildFragmentManager().getFragments().get(0);
                if (childfragment instanceof TabsFragment) {
                    try {
                        ((TabsFragment) childfragment).load();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                navigationView.getMenu().getItem(3).setVisible(editmode);
                navigationView.getMenu().getItem(4).setVisible(editmode);
            }
        });
        navigationView.getMenu().getItem(3).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (button_vibration) {
                    Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);


                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.addtabdialog, null);
                EditText editText_name = view.findViewById(R.id.dialogtab_editText_name);


                mBuilder.setView(view)
                        .setTitle(R.string.menu_add);
                mBuilder.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (button_vibration) {
                            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            assert vr != null;
                            vr.vibrate(100);
                        }
                        String tabname = editText_name.getText().toString().trim();

                        SharedPreferences p = getSharedPreferences("appsettings", MODE_PRIVATE);
                        String tabsString = p.getString("tabs", null);
                        List<String> tabs = new ArrayList<String>();
                        if (tabsString != null) {
                            try {
                                JSONArray tabsArray = new JSONArray(tabsString);
                                for (int i = 0; i < tabsArray.length(); i++) {
                                    tabs.add(tabsArray.getString(i));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        if (tabs.contains(tabname)) {

                            AlertDialog mDialog = new AlertDialog.Builder(MainActivity.this)
                                    .setTitle(getString(R.string.tabname))
                                    .setMessage(getString(R.string.tabname_already_exist))

                                    // 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(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            if (button_vibration) {
                                                Vibrator vr = (Vibrator) 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();
                            return;
                        }
                        if (tabname.isEmpty()) {

                            AlertDialog mDialog = new AlertDialog.Builder(MainActivity.this)
                                    .setTitle(getString(R.string.tabname))
                                    .setMessage(getString(R.string.invalid))

                                    // 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(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            if (button_vibration) {
                                                Vibrator vr = (Vibrator) 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();
                            return;
                        }
                        MenuItem item = navigationView.getMenu().add(R.id.dynamicgroup, lastID++, 3, tabname);
                        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                if (button_vibration) {
                                    Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                                    assert vr != null;
                                    vr.vibrate(100);
                                }
                                DrawerLayout mDrawerLayout;
                                mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
                                mDrawerLayout.closeDrawer(GravityCompat.START);
                                Objects.requireNonNull(getSupportActionBar()).setTitle(tabname);
                                Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
                                NavHostFragment nhf = (NavHostFragment) currentFragment;
                                assert nhf != null;
                                nhf.getChildFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new TabsFragment(tabname)).commit();
                                return true;
                            }
                        });
                        tabitems.put(tabname, item);


                        tabs.add(tabname);
                        SharedPreferences.Editor editor = p.edit();
                        editor.putString("tabs", new JSONArray(tabs).toString());
                        editor.apply();

                    }
                });
                mBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (button_vibration) {
                            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            assert vr != null;
                            vr.vibrate(100);
                        }

                    }
                });
                AlertDialog mDialog = mBuilder.create();
                Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawableResource(R.drawable.button_round);
                mDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
                mDialog.show();
                return true;
            }
        });
        navigationView.getMenu().getItem(4).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (button_vibration) {
                    Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                SharedPreferences p = getSharedPreferences("appsettings", MODE_PRIVATE);
                String tabsString = p.getString("tabs", null);
                List<String> tabs = new ArrayList<String>();
                if (tabsString != null) {
                    try {
                        JSONArray tabsArray = new JSONArray(tabsString);
                        for (int i = 0; i < tabsArray.length(); i++) {
                            tabs.add(tabsArray.getString(i));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                List<String> selectedTabs = new ArrayList<>();
                String[] tabsarray = tabs.toArray(new String[0]);
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                mBuilder.setTitle(R.string.menu_remove);

                mBuilder.setMultiChoiceItems(tabsarray, null, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
                        String selectedItem = tabsarray[i];
                        if (isChecked) {
                            selectedTabs.add(selectedItem);
                        } else {
                            selectedTabs.remove(selectedItem);
                        }
                    }
                });
                mBuilder.setPositiveButton(getString(R.string.remove), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (button_vibration) {
                            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            assert vr != null;
                            vr.vibrate(100);
                        }
                        tabs.removeAll(selectedTabs);
                        SharedPreferences.Editor editor = p.edit();
                        editor.putString("tabs", new JSONArray(tabs).toString());
                        for (String tab : selectedTabs) {
                            editor.remove("listItems." + tab);
                            editor.apply();
                            navigationView.getMenu().removeItem(tabitems.get(tab).getItemId());
                            tabitems.remove(tab);
                            dialogInterface.dismiss();

                        }
                    }
                });
                mBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (button_vibration) {
                            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            assert vr != null;
                            vr.vibrate(100);
                        }
                    }
                });
                AlertDialog mDialog = mBuilder.create();
                Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawableResource(R.drawable.button_round);
                mDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
                mDialog.show();
                return true;
            }
        });
        String tabsString = p.getString("tabs", null);
        List<String> tabs = new ArrayList<>();
        if (tabsString != null) {
            try {
                JSONArray tabsArray = new JSONArray(tabsString);
                for (int i = 0; i < tabsArray.length(); i++) {
                    tabs.add(tabsArray.getString(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        for (String tab : tabs) {
            MenuItem item = navigationView.getMenu().add(R.id.dynamicgroup, lastID++, 3, tab);
            item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    if (button_vibration) {
                        Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        assert vr != null;
                        vr.vibrate(100);
                    }
                    DrawerLayout mDrawerLayout;
                    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
                    mDrawerLayout.closeDrawer(GravityCompat.START);
                    Objects.requireNonNull(getSupportActionBar()).setTitle(tab);
                    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
                    NavHostFragment nhf = (NavHostFragment) currentFragment;
                    assert nhf != null;
                    nhf.getChildFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new TabsFragment(tab)).commit();
                    return true;
                }
            });
            tabitems.put(tab, item);
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        for (int i = 0; i < menu.size(); i++) {
            MenuItem menuItem = menu.getItem(i);
            SpannableString spannable = new SpannableString(
                    menu.getItem(i).getTitle().toString()
            );
            TypedValue typedValue = new TypedValue();
            Resources.Theme theme = getTheme();
            theme.resolveAttribute(R.attr.colorOnPrimary, typedValue, true);
            int color = typedValue.data;
            spannable.setSpan(new ForegroundColorSpan(color),
                    0, spannable.length(), 0);
            menuItem.setTitle(spannable);
        }

        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
    }


    public void menurighttopsettings(MenuItem i) {
        if (button_vibration) {
            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            assert vr != null;
            vr.vibrate(100);
        }
        Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        NavHostFragment nhf = (NavHostFragment) currentFragment;
        nhf.getChildFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new SettingsFragment()).commit();
        Objects.requireNonNull(getSupportActionBar()).setTitle(R.string.menu_settings);
    }

    public void menurighttopabout(MenuItem i) {
        if (button_vibration) {
            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            assert vr != null;
            vr.vibrate(100);
        }
        Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        NavHostFragment nhf = (NavHostFragment) currentFragment;
        nhf.getChildFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new CreditsFragment()).commit();
        Objects.requireNonNull(getSupportActionBar()).setTitle(R.string.menu_about);
    }

    public void menurighttopdocumentation(MenuItem i) {
        if (button_vibration) {
            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            assert vr != null;
            vr.vibrate(100);
        }
        AlertDialog mDialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.menu_documentation))
                .setMessage(getString(R.string.you_will_be_redirected))

                // 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 (button_vibration) {
                            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            assert vr != null;
                            vr.vibrate(100);
                        }
                        Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.jg-cody.de/teraplex"));
                        startActivity(in);
                    }
                })

                // 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 (button_vibration) {
                            Vibrator vr = (Vibrator) 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();


    }

    public void menurighttopcloseapp(MenuItem i) {
        if (button_vibration) {
            Vibrator vr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            assert vr != null;
            vr.vibrate(100);
        }
        finishAndRemoveTask();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            // String picturePath contains the path of selected Image
            try {
                InputStream Background = getContentResolver().openInputStream(selectedImage);
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                int len;
                byte[] buf = new byte[1024];
                while (true) {
                    assert Background != null;
                    if (!((len = Background.read(buf)) > 0)) break;
                    bOut.write(buf, 0, len);
                }
                Background.close();
                SharedPreferences p = getSharedPreferences("appsettings", Context.MODE_PRIVATE);
                p.edit().putString("Background", Base64.encodeToString(bOut.toByteArray(), Base64.DEFAULT)).apply();
                loadBackground();
                startActivity(getIntent());
                finish();

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (requestCode == CREATE_FILE && resultCode == RESULT_OK && null != data) {
            try {
                ParcelFileDescriptor pfd = getContentResolver().
                        openFileDescriptor(data.getData(), "w");
                FileOutputStream fileOutputStream =
                        new FileOutputStream(pfd.getFileDescriptor());
                JSONObject jsonObject = new JSONObject();
                List<String> listTabs = getTabsFromPrefs();
                jsonObject.put("tabs", new JSONArray(listTabs));
                JSONObject jsonTabs = new JSONObject();
                SharedPreferences p = this.getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
                for (String tab : listTabs) {
                    String listItems = p.getString("listItems." + tab, "[]");
                    JSONArray listItems2 = new JSONArray(listItems);
                    jsonTabs.put(tab, listItems2);
                }
                jsonObject.put("tabitems", jsonTabs);

                fileOutputStream.write(jsonObject.toString().getBytes());
                // Let the document provider know you're done by closing the stream.
                fileOutputStream.close();
                pfd.close();
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }

        } else if (requestCode == PICK_PDF_FILE && resultCode == RESULT_OK && null != data) {
            try {
                ParcelFileDescriptor pfd = getContentResolver().
                        openFileDescriptor(data.getData(), "r");
                FileInputStream fileInputStream =
                        new FileInputStream(pfd.getFileDescriptor());
                BufferedReader bf = new BufferedReader(new InputStreamReader(fileInputStream));
                String s = bf.readLine();
                JSONObject jso = new JSONObject(s);
                SharedPreferences p = this.getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
                JSONArray tabs = jso.getJSONArray("tabs");
                SharedPreferences.Editor sharedEditor = p.edit();
                sharedEditor.putString("tabs", tabs.toString());
                JSONObject tabitems = jso.getJSONObject("tabitems");

                for (int i = 0; i < tabs.length(); i++) {
                    String tab = tabs.getString(i);
                    JSONArray tArray = tabitems.getJSONArray(tab);
                    sharedEditor.putString("listItems." + tab, tArray.toString());

                }
                sharedEditor.apply();
                startActivity(getIntent());
                finish();
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void loadBackground() {
        SharedPreferences p = getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        String Background = p.getString("Background", null);
        ImageView I = findViewById(R.id.Background);
        byte[] BA = Base64.decode(Background, Base64.DEFAULT);
        I.setImageBitmap(BitmapFactory.decodeByteArray(BA, 0, BA.length));
    }

    public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static Bitmap scaleCenterCrop(Bitmap source, int newHeight,
                                         int newWidth) {
        int sourceWidth = source.getWidth();
        int sourceHeight = source.getHeight();

        float xScale = (float) newWidth / sourceWidth;
        float yScale = (float) newHeight / sourceHeight;
        float scale = Math.max(xScale, yScale);

        // Now get the size of the source bitmap when scaled
        float scaledWidth = scale * sourceWidth;
        float scaledHeight = scale * sourceHeight;

        float left = (newWidth - scaledWidth) / 2;
        float top = (newHeight - scaledHeight) / 2;

        RectF targetRect = new RectF(left, top, left + scaledWidth, top
                + scaledHeight);//from ww w  .j a va 2s. co m

        Bitmap dest = Bitmap.createBitmap(newWidth, newHeight,
                source.getConfig());
        Canvas canvas = new Canvas(dest);
        canvas.drawBitmap(source, null, targetRect, null);

        return dest;
    }

    //muss oben noch ausgebessert werden
    public List<String> getTabsFromPrefs() {
        SharedPreferences p = getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        String tabsString = p.getString("tabs", null);
        List<String> tabs = new ArrayList<String>();
        if (tabsString != null) {
            try {
                JSONArray tabsArray = new JSONArray(tabsString);
                for (int i = 0; i < tabsArray.length(); i++) {
                    tabs.add(tabsArray.getString(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return tabs;
    }


}
