package de.jg_cody.Teraplex;

import android.app.Activity;
import android.content.Context;
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.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Locale;

import de.jg_cody.Teraplex.ui.Credits.CreditsFragment;
import de.jg_cody.Teraplex.ui.Einstellungen.EinstellungenFragment;
import de.jg_cody.Teraplex.ui.Konsole.KonsoleFragment;
import de.jg_cody.Teraplex.ui.home.HomeFragment;


public class MainActivity extends AppCompatActivity implements AddButtonDialogSingle.AddButtonDialogListener {
    public static int RESULT_LOAD_IMAGE = 0;
    private AppBarConfiguration mAppBarConfiguration;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @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));
        if (savedInstanceState == null) {
            /*getSupportFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new DemoPreferenceFragment())
                    .commit();
            NonDeveloperMessage.maybeShow(this);*/
        }
        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());

        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);


        FloatingActionButton mfab = findViewById(R.id.fab);
        mfab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Log.d("I", "ACTION BUTTON CLICKED");
                    SSH_connection.executeRemoteCommand(HomeFragment.ip, HomeFragment.user, HomeFragment.password, KonsoleFragment.command);
                } catch (Exception e) {
                }
            }
        });
        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_einstellungen, R.id.nav_kueche, R.id.nav_zeitsteuerung, R.id.nav_schlafzimmer, R.id.nav_flur, R.id.nav_über, R.id.nav_konsole)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);


    }


    /*static public class DemoPreferenceFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            addPreferencesFromResource(R.xml.preferences);
        }

        @Override
        public void onDisplayPreferenceDialog(Preference preference) {
            if (preference instanceof ColorPreference) {
                ((ColorPreference) preference).showDialog(this, 0);
            } else super.onDisplayPreferenceDialog(preference);
        }
    }*/
    @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);
    }



    @Override
    public void applyTexts(String username, String password) {

    }

    public void menurighttopeinstellungen(MenuItem i) {
        EinstellungenFragment pef = new EinstellungenFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.nav_host_fragment, pef).setPrimaryNavigationFragment(pef);
        transaction.addToBackStack(null);
        transaction.commit();
        getSupportActionBar().setTitle(R.string.menu_einstellungen);
    }

    public void menurighttopcredits(MenuItem i) {
        CreditsFragment pef = new CreditsFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.nav_host_fragment, pef).setPrimaryNavigationFragment(pef);
        transaction.addToBackStack(null);
        transaction.commit();
        getSupportActionBar().setTitle(R.string.menu_über);
    }

    public void menurighttopdocumentation(MenuItem i) {
        Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.jg-cody.de/"));
        startActivity(in);
    }

    public void menurighttopschliessen(MenuItem i) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            finishAffinity();
        } else {
            finishAndRemoveTask();
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.O)
    @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};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, 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 ((len = Background.read(buf)) > 0) {
                    bOut.write(buf, 0, len);
                }
                Background.close();
                SharedPreferences p = getSharedPreferences("appsettings", Context.MODE_PRIVATE);
                p.edit().putString("Background", Base64.getEncoder().encodeToString(bOut.toByteArray())).apply();
                loadBackground();
                startActivity(getIntent());
                finish();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    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.getDecoder().decode(Background);
        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;
    }

    public static Bitmap createImage(int width, int height, int color) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(color);
        canvas.drawRect(0F, 0F, (float) width, (float) height, paint);
        return bitmap;
    }
}
