package com.example.onetap_ssh.ui.tabs;

import static android.content.Context.MODE_PRIVATE;

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.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Objects;

import com.example.onetap_ssh.AddButtonDialogSingle;
import com.example.onetap_ssh.AddButtonsDialogDouble;
import com.example.onetap_ssh.AddHeadlineDialog;
import com.example.onetap_ssh.MainActivity;
import com.example.onetap_ssh.R;

public class TabsFragment extends Fragment implements AddButtonDialogSingle.AddButtonDialogListenerSingle, AddButtonsDialogDouble.AddButtonsDialogListenerDouble, AddHeadlineDialog.AddHeadlineDialogListener {


    String[] commands = {"Hello1", "Hello2", "Hello3", "Hello4", "Hello5"};
    int[] type = {0, 1, 0, 0, 1};

    RecyclerView listView;
    ListAdapter listAdapter;
    FloatingActionButton addfab;

    ArrayList<ListItem> items;


    String tabname;


    public TabsFragment(String tabname) {
        this.tabname = tabname;

    }

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

        View root = inflater.inflate(R.layout.fragment_tabs, 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);
        }


        listView = root.findViewById(R.id.listView);

        items = new ArrayList<ListItem>();


        listAdapter = new ListAdapter(getContext(), items, tabname);
        listView.setLayoutManager(new LinearLayoutManager(getContext()));
        listView.setAdapter(listAdapter);

        ItemTouchHelper h = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
                //listAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                listAdapter.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                try {
                    save();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) {
                listAdapter.remove(viewHolder.getAdapterPosition());
                try {
                    save();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return MainActivity.editmode;
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return MainActivity.editmode;

            }
        });
        h.attachToRecyclerView(listView);

        addfab = root.findViewById(R.id.fab);
        if (MainActivity.editmode) {
            addfab.setVisibility(View.VISIBLE);
        } else {
            addfab.setVisibility(View.GONE);
        }
        addfab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChooseElement();
            }
        });
        try {
            load();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return root;
    }

    private void showChooseElement() {
        final String[] listItems = {getString(R.string.single_button), getString(R.string.double_button), getString(R.string.heading), getString(R.string.space)};
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
        mBuilder.setTitle(getString(R.string.choose_element));
        mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i == 0) {
                    openDialog1();
                } else if (i == 1) {
                    openDialog2();
                } else if (i == 2) {
                    openDialog3();
                } else if (i == 3) {
                    listAdapter.add(new ListItemSpace());
                    try {
                        save();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

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

    public void openDialog1() {
        AddButtonDialogSingle addButtonDialogSingle = new AddButtonDialogSingle();
        addButtonDialogSingle.setFragment(this);
        addButtonDialogSingle.show(requireActivity().getSupportFragmentManager(), getString(R.string.single_button));

    }

    public void openDialog2() {
        AddButtonsDialogDouble addButtonsDialogDouble = new AddButtonsDialogDouble();
        addButtonsDialogDouble.setFragment(this);
        addButtonsDialogDouble.show(requireActivity().getSupportFragmentManager(), getString(R.string.double_button));
    }

    public void openDialog3() {
        AddHeadlineDialog addHeadlineDialog = new AddHeadlineDialog();
        addHeadlineDialog.setFragment(this);
        addHeadlineDialog.show(requireActivity().getSupportFragmentManager(), getString(R.string.heading));
    }

    @Override
    public void applyTextsSingle(String name, String command, String button) {
        //items.add(new ListItemSingle(0,name,command,button));
        listAdapter.add(new ListItemSingle(name, command, button));
        try {
            save();
        } catch (JSONException e) {
            e.printStackTrace();
        }

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

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

    @Override
    public void applyTextsDouble(String name, String command1, String command2, String button1, String button2) {
        listAdapter.add(new ListItemDouble(name, command1, command2, button1, button2));
        try {
            save();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void applyTextsHeadline(String headline) {
        listAdapter.add(new ListItemHeadline(headline));
        try {
            save();
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    public void load() throws JSONException {
        if (MainActivity.editmode) {
            addfab.setVisibility(View.VISIBLE);
        } else {
            addfab.setVisibility(View.GONE);
        }
        listAdapter.clear();
        SharedPreferences p = requireContext().getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        String listItems = p.getString("listItems." + tabname, "[]");
        JSONArray listItems2 = new JSONArray(listItems);
        for (int i = 0; i < listItems2.length(); i++) {
            JSONObject item = listItems2.getJSONObject(i);
            listAdapter.add(ListItem.fromJson(item));
        }

    }

    public static void save(String tabname, Context context, ListAdapter listAdapter) throws JSONException {
        JSONArray listItems2 = new JSONArray();
        for (ListItem Item : listAdapter.getObjects()) {
            listItems2.put(Item.toJson());
        }
        SharedPreferences.Editor editor = context.getSharedPreferences("appsettings", MODE_PRIVATE).edit();
        editor.putString("listItems." + tabname, listItems2.toString());
        editor.apply();
    }

    public void save() throws JSONException {
        save(tabname, requireContext(), listAdapter);
    }
}
