/* Copyright 2019 Thomas Schneider
 *
 * This file is a part of Fedilab
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with Fedilab; if not,
 * see <http://www.gnu.org/licenses>. */
package app.fedilab.android.activities;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import org.jetbrains.annotations.NotNull;

import app.fedilab.android.R;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.fragments.DisplayAdminAccountsFragment;
import app.fedilab.android.fragments.DisplayAdminReportsFragment;
import app.fedilab.android.helper.Helper;


/**
 * Created by Thomas on 19/06/2019.
 * Admin activity
 */

public class AdminActivity extends BaseActivity {


    private boolean unresolved;
    private boolean local, remote, active, pending, disabled, silenced, suspended;
    private DisplayAdminReportsFragment displayAdminReportsFragment;
    private DisplayAdminAccountsFragment displayAdminAccountsFragment;


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

        setTheme(R.style.AppAdminTheme);

        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
            assert inflater != null;
            View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(AdminActivity.this), false);
            view.setBackground(new ColorDrawable(ContextCompat.getColor(AdminActivity.this, R.color.cyanea_primary)));
            actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
            TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
            toolbar_close.setOnClickListener(v -> finish());
            toolbar_title.setText(String.format(getString(R.string.administration) + " %s", Helper.getLiveInstance(AdminActivity.this)));
        }
        setContentView(R.layout.activity_admin);
        unresolved = local = active = true;
        remote = pending = disabled = silenced = suspended = false;
        ViewPager admin_viewpager = findViewById(R.id.admin_viewpager);

        TabLayout admin_tablayout = findViewById(R.id.admin_tablayout);
        admin_tablayout.setBackgroundColor(ContextCompat.getColor(AdminActivity.this, R.color.cyanea_primary));
        admin_tablayout.addTab(admin_tablayout.newTab().setText(getString(R.string.reports)));
        admin_tablayout.addTab(admin_tablayout.newTab().setText(getString(R.string.accounts)));


        final LinearLayout tabStrip = (LinearLayout) admin_tablayout.getChildAt(0);
        tabStrip.getChildAt(0).setOnLongClickListener(v -> {
            PopupMenu popup = new PopupMenu(AdminActivity.this, tabStrip.getChildAt(0));
            popup.getMenuInflater()
                    .inflate(R.menu.option_filter_admin_reports, popup.getMenu());
            Menu menu = popup.getMenu();
            final MenuItem itemUnresolved = menu.findItem(R.id.action_unresolved_reports);


            itemUnresolved.setChecked(unresolved);

            popup.setOnDismissListener(menu12 -> {
                FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
                fragTransaction.detach(displayAdminReportsFragment);
                Bundle bundle = new Bundle();
                bundle.putBoolean("unresolved", unresolved);
                displayAdminReportsFragment.setArguments(bundle);
                fragTransaction.attach(displayAdminReportsFragment);
                fragTransaction.commit();
            });
            popup.setOnMenuItemClickListener(item -> {
                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
                item.setActionView(new View(AdminActivity.this));
                item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {
                        return false;
                    }

                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        return false;
                    }
                });
                if (item.getItemId() == R.id.action_unresolved_reports) {
                    unresolved = !unresolved;
                }
                itemUnresolved.setChecked(unresolved);
                return false;
            });
            popup.show();
            return true;
        });


        tabStrip.getChildAt(1).setOnLongClickListener(v -> {
            PopupMenu popup = new PopupMenu(AdminActivity.this, tabStrip.getChildAt(1));
            popup.getMenuInflater()
                    .inflate(R.menu.option_filter_admin_accounts, popup.getMenu());
            Menu menu = popup.getMenu();
            final MenuItem itemLocal = menu.findItem(R.id.action_local);
            final MenuItem itemRemote = menu.findItem(R.id.action_remote);
            final MenuItem itemActive = menu.findItem(R.id.action_active);
            final MenuItem itemPending = menu.findItem(R.id.action_pending);
            final MenuItem itemDisabled = menu.findItem(R.id.action_disabled);
            final MenuItem itemSilenced = menu.findItem(R.id.action_silenced);
            final MenuItem itemSuspended = menu.findItem(R.id.action_suspended);
            if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
                itemSilenced.setVisible(false);
                itemPending.setVisible(false);
                itemSuspended.setVisible(false);
            }

            itemLocal.setChecked(local);
            itemRemote.setChecked(remote);
            itemActive.setChecked(active);
            itemPending.setChecked(pending);
            itemDisabled.setChecked(disabled);
            itemSilenced.setChecked(silenced);
            itemSuspended.setChecked(suspended);

            popup.setOnDismissListener(menu1 -> {
                FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
                fragTransaction.detach(displayAdminAccountsFragment);
                Bundle bundle = new Bundle();
                bundle.putBoolean("local", local);
                bundle.putBoolean("remote", remote);
                bundle.putBoolean("active", active);
                bundle.putBoolean("pending", pending);
                bundle.putBoolean("disabled", disabled);
                bundle.putBoolean("silenced", silenced);
                bundle.putBoolean("suspended", suspended);
                displayAdminAccountsFragment.setArguments(bundle);
                fragTransaction.attach(displayAdminAccountsFragment);
                fragTransaction.commit();

            });
            popup.setOnMenuItemClickListener(item -> {

                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
                item.setActionView(new View(AdminActivity.this));
                item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {
                        return false;
                    }

                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        return false;
                    }
                });
                switch (item.getItemId()) {
                    case R.id.action_local:
                        if (!local) {
                            remote = false;
                            local = true;
                        }
                        break;
                    case R.id.action_remote:
                        if (!remote) {
                            remote = true;
                            local = false;
                        }
                        break;
                    case R.id.action_active:
                        if (!active) {
                            active = true;
                            pending = false;
                            disabled = false;
                            silenced = false;
                            suspended = false;
                        }
                        break;
                    case R.id.action_pending:
                        if (!pending) {
                            pending = true;
                            active = false;
                            disabled = false;
                            silenced = false;
                            suspended = false;
                        }
                        break;
                    case R.id.action_disabled:
                        if (!disabled) {
                            disabled = true;
                            active = false;
                            pending = false;
                            silenced = false;
                            suspended = false;
                        }
                        break;
                    case R.id.action_silenced:
                        if (!silenced) {
                            silenced = true;
                            active = false;
                            pending = false;
                            disabled = false;
                            suspended = false;
                        }
                        break;
                    case R.id.action_suspended:
                        if (!suspended) {
                            suspended = true;
                            active = false;
                            pending = false;
                            disabled = false;
                            silenced = false;
                        }
                        break;
                }

                itemLocal.setChecked(local);
                itemRemote.setChecked(remote);
                itemActive.setChecked(active);
                itemPending.setChecked(pending);
                itemDisabled.setChecked(disabled);
                itemSilenced.setChecked(silenced);
                itemSuspended.setChecked(suspended);
                return false;
            });
            popup.show();
            return true;
        });


        PagerAdapter mPagerAdapter = new AdminPagerAdapter(getSupportFragmentManager());
        admin_viewpager.setAdapter(mPagerAdapter);
        admin_viewpager.setOffscreenPageLimit(2);
        admin_viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(admin_tablayout));
        admin_tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                admin_viewpager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                Fragment fragment = null;
                if (admin_viewpager.getAdapter() != null)
                    fragment = (Fragment) admin_viewpager.getAdapter().instantiateItem(admin_viewpager, tab.getPosition());
                switch (tab.getPosition()) {
                    case 0:
                        if (fragment != null) {
                            displayAdminReportsFragment = ((DisplayAdminReportsFragment) fragment);
                            displayAdminReportsFragment.scrollToTop();
                        }
                        break;
                    case 1:
                        if (fragment != null) {
                            displayAdminAccountsFragment = ((DisplayAdminAccountsFragment) fragment);
                            displayAdminAccountsFragment.scrollToTop();
                        }
                        break;

                }
            }
        });

    }


    private class AdminPagerAdapter extends FragmentStatePagerAdapter {

        AdminPagerAdapter(FragmentManager fm) {
            super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        @NotNull
        @Override
        public Fragment getItem(int position) {
            Bundle bundle;
            if (position == 0) {
                displayAdminReportsFragment = new DisplayAdminReportsFragment();
                bundle = new Bundle();
                bundle.putBoolean("unresolved", unresolved);
                displayAdminReportsFragment.setArguments(bundle);
                return displayAdminReportsFragment;
            }
            displayAdminAccountsFragment = new DisplayAdminAccountsFragment();
            bundle = new Bundle();
            bundle.putBoolean("local", local);
            bundle.putBoolean("remote", remote);
            bundle.putBoolean("active", active);
            bundle.putBoolean("pending", pending);
            bundle.putBoolean("disabled", disabled);
            bundle.putBoolean("silenced", silenced);
            bundle.putBoolean("suspended", suspended);
            displayAdminAccountsFragment.setArguments(bundle);
            return displayAdminAccountsFragment;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

        }

        @Override
        public int getCount() {
            return 2;
        }
    }

}
