package com.example.onetap_ssh;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.LayoutInflater;

import com.example.onetap_ssh.fragment.AboutFragment;
import com.example.onetap_ssh.fragment.SettingsFragment;
import com.example.onetap_ssh.ui.tabs.TabsFragment;
import com.example.onetap_ssh.util.DialogUtil;
import com.example.onetap_ssh.util.NavigationUtil;
import com.example.onetap_ssh.util.SettingsUtil;
import com.example.onetap_ssh.util.ThemeUtil;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.appcompat.app.ActionBar;
import androidx.core.view.GravityCompat;
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 androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import com.example.onetap_ssh.databinding.ActivityMainBinding;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;

    private boolean fullyLaunched;
    public static boolean button_vibration = false;
    private boolean lockOnStop = true;

    public static boolean editmode = false;
    int lastID = 6969;
    Map<String, MenuItem> tabitems = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);
        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = binding.navView;
        // 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_about)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
        SharedPreferences p = getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        button_vibration = p.getBoolean("Vibration",  false );
        IntroActivity.show_logoanimation = p.getBoolean("Logoanimation",  true );
        launchApp();

        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.menu_main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
    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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public void openSettings(MenuItem item) {
        NavigationUtil.navigate(this, SettingsFragment.class, null);
    }
    public void openAbout(MenuItem item) {
        NavigationUtil.navigate(this, AboutFragment.class, null);
    }
    public void lockApp(MenuItem item) {

    }
    private void launchApp() {
        fullyLaunched = true;
        lockOnStop = true;

        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ThemeUtil.loadBackground(this);

               
        if(SettingsUtil.isFirstLaunch(this) && SettingsUtil.getGroups(this).isEmpty()) {
            SettingsUtil.addGroup(this, UUID.randomUUID().toString(), "My Codes");
            DialogUtil.showYesNo(this, R.string.enable_encryption_title, R.string.enable_encryption_message, () -> NavigationUtil.navigate(this, SettingsFragment.class, null), null);
            SettingsUtil.setFirstLaunch(this, false);
        }

        Fragment fragment = NavigationUtil.getCurrentFragment(this);
        
    }
    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;
    }
    public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

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