/*
 * Copyright (C) 2014 Andrew Comminos
 *
 * 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.lublin.mumla.servers;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import se.lublin.humla.model.Server;
import se.lublin.mumla.R;
import se.lublin.mumla.Settings;
import se.lublin.mumla.db.DatabaseProvider;
import se.lublin.mumla.db.MumlaDatabase;
import se.lublin.mumla.db.PublicServer;

/**
 * Displays a list of public servers that can be connected to, sorted, and favourited.
 * @author morlunk
 *
 */
public class PublicServerListFragment extends Fragment implements OnItemClickListener, PublicServerAdapter.PublicServerAdapterMenuListener {

    private FavouriteServerListFragment.ServerConnectHandler mConnectHandler;
    private DatabaseProvider mDatabaseProvider;
    private List<PublicServer> mServers;
    private GridView mServerGrid;
    private ProgressBar mServerProgress;
    private PublicServerAdapter mServerAdapter;

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

        setHasOptionsMenu(true);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mConnectHandler = (FavouriteServerListFragment.ServerConnectHandler)activity;
            mDatabaseProvider = (DatabaseProvider) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()+" must implement ServerConnectHandler and DatabaseProvider!");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        fillPublicList();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_public_server_list, container, false);
        mServerGrid = view.findViewById(R.id.server_list_grid);
        mServerGrid.setOnItemClickListener(this);
        if(mServerAdapter != null)
            mServerGrid.setAdapter(mServerAdapter);
        mServerProgress = view.findViewById(R.id.serverProgress);
        mServerProgress.setVisibility(mServerAdapter == null ? View.VISIBLE : View.GONE);
        return view;
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.findItem(R.id.menu_match_server).setVisible(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_public_server_list, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (isFilled()) {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_match_server) {
                showMatchDialog();
            } else if (itemId == R.id.menu_sort_server_item) {
                showSortDialog();
                return true;
            } else if (itemId == R.id.menu_search_server_item) {
                showFilterDialog();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void favouriteServer(final Server server) {
        final Settings settings = Settings.getInstance(requireActivity());
        final EditText usernameField = new EditText(requireActivity());
        usernameField.setHint(settings.getDefaultUsername());
        FrameLayout layout = new FrameLayout(requireActivity());
        layout.addView(usernameField);
        int horizontalPadding = (int) getResources().getDimension(R.dimen.padding_medium);
        layout.setPadding(horizontalPadding, 0, horizontalPadding, 0);
        new MaterialAlertDialogBuilder(requireActivity())
                .setTitle(R.string.addFavorite)
                .setView(layout)
                .setPositiveButton(R.string.add, (dialog, which) -> {
                    if (usernameField.getText().length() > 0) {
                        server.setUsername(usernameField.getText().toString());
                    } else {
                        server.setUsername(settings.getDefaultUsername());
                    }
                    MumlaDatabase database = mDatabaseProvider.getDatabase();
                    database.addServer(server);
                })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    public void setServers(List<PublicServer> servers) {
        mServers = servers;
        mServerProgress.setVisibility(View.GONE);
        mServerAdapter = new PublicServerAdapter(getActivity(), servers, this);
        mServerGrid.setAdapter(mServerAdapter);
    }

    public boolean isFilled() {
        return mServerAdapter != null;
    }

    private void showMatchDialog() {
        new MaterialAlertDialogBuilder(requireActivity())
                .setTitle(R.string.server_match)
                .setMessage(R.string.server_match_description)
                .setPositiveButton(R.string.search, (dialog, which) -> findOptimalServer())
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    private void findOptimalServer() {
        MatchServerTask matchServerTask = new MatchServerTask();
        matchServerTask.execute(Locale.getDefault().getCountry());
    }

    private void showSortDialog() {
        new MaterialAlertDialogBuilder(requireActivity())
                .setTitle(R.string.sortBy)
                .setItems(new String[]{getString(R.string.name), getString(R.string.country)}, new SortClickListener())
                .show();
    }

    private void showFilterDialog() {
        View dialogView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_server_search, null);
        final EditText nameText = dialogView.findViewById(R.id.server_search_name);
        final EditText countryText = dialogView.findViewById(R.id.server_search_country);

        final AlertDialog alertDialog = new MaterialAlertDialogBuilder(getActivity())
                .setTitle(R.string.search)
                .setView(dialogView)
                .setPositiveButton(R.string.search, (dialog, which) -> {
                    String queryName = nameText.getText().toString().toUpperCase(Locale.US);
                    String queryCountry = countryText.getText().toString().toUpperCase(Locale.US);
                    mServerAdapter.filter(queryName, queryCountry);
                    dialog.dismiss();
                })
                .create();

        nameText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        nameText.setOnEditorActionListener((v, actionId, event) -> {
            String queryName = nameText.getText().toString().toUpperCase(Locale.US);
            String queryCountry = countryText.getText().toString().toUpperCase(Locale.US);
            mServerAdapter.filter(queryName, queryCountry);
            alertDialog.dismiss();
            return true;
        });

        countryText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        countryText.setOnEditorActionListener((v, actionId, event) -> {
            String queryName = nameText.getText().toString().toUpperCase(Locale.US);
            String queryCountry = countryText.getText().toString().toUpperCase(Locale.US);
            mServerAdapter.filter(queryName, queryCountry);
            alertDialog.dismiss();
            return true;
        });

        // Show keyboard automatically
        nameText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        });

        alertDialog.show();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        mConnectHandler.connectToPublicServer(mServerAdapter.getItem(arg2));
    }

    private void fillPublicList() {
        new PublicServerFetchTask(getActivity()) {
            protected void onPostExecute(List<PublicServer> result) {
                super.onPostExecute(result);

                if (result == null) {
                    Context context = contextRef.get();
                    if (context != null) {
                        Toast.makeText(context, R.string.error_fetching_servers, Toast.LENGTH_SHORT).show();
                    }
                    return;
                }

                if(isVisible()) // Prevents NPEs when fragment is detached.
                    setServers(result);
            };
        }.execute();
    }

    private class SortClickListener implements DialogInterface.OnClickListener {

        private static final int SORT_NAME = 0;
        private static final int SORT_COUNTRY = 1;

        private Comparator<PublicServer> nameComparator = new Comparator<PublicServer>() {
            @Override
            public int compare(PublicServer lhs, PublicServer rhs) {
                return lhs.getName().compareTo(rhs.getName());
            }
        };

        private Comparator<PublicServer> countryComparator = new Comparator<PublicServer>() {
            @Override
            public int compare(PublicServer lhs, PublicServer rhs) {
                if(rhs.getCountry() == null) return -1;
                else if(lhs.getCountry() == null) return 1;
                return lhs.getCountry().compareTo(rhs.getCountry());
            }
        };


        @Override
        public void onClick(DialogInterface dialog, int which) {
            ArrayAdapter<PublicServer> arrayAdapter = mServerAdapter;
            if(which == SORT_NAME) {
                arrayAdapter.sort(nameComparator);
            } else if(which == SORT_COUNTRY) {
                arrayAdapter.sort(countryComparator);
            }
        }
    }

    /**
     * Finds an empty server in the user's country code with low latency.
     * By default, it will show a ProgressDialog while it performs this and an AlertDialog allowing the user to connect.
     */
    private class MatchServerTask extends AsyncTask<String, Void, ServerInfoResponse> {

        /**
         * Query until we find up to SEARCH_RANGE empty servers that meet the zero user and location requirements.
         * Once we have that, then we'll sort them based on latency.
         * TODO make this a user-changeable option.
         */
        public static final int SEARCH_RANGE = 20;

        private Comparator<ServerInfoResponse> mLatencyComparator = new Comparator<ServerInfoResponse>() {
            @Override
            public int compare(ServerInfoResponse lhs, ServerInfoResponse rhs) {
                return lhs.getLatency() == rhs.getLatency() ? 0 :
                        lhs.getLatency() < rhs.getLatency() ? -1 : 1;
            }
        };

        private class MatchServerInfoTask extends ServerInfoTask {
            @Override
            protected void onPostExecute(ServerInfoResponse serverInfoResponse) {
                mResponseCount++;
                if(serverInfoResponse == null) {
                    // TODO handle bad responses
                } else if(serverInfoResponse.getCurrentUsers() == 0 &&
                        serverInfoResponse.getVersion() == se.lublin.humla.Constants.PROTOCOL_VERSION) {
                    mGoodResponses.add(serverInfoResponse);
                }

                // Once we have a good sample of results, shut down the ping threads.
                if(mResponseCount >= mResponsesToSend) {
                    synchronized (mLock) {
                        mLock.notify();
                    }
                    mPingExecutor.shutdownNow();
                }
            }

        }

        private ExecutorService mPingExecutor = Executors.newFixedThreadPool(5); // Run 5 concurrent pings at a time
        private Object mLock = new Object();

        private List<ServerInfoResponse> mGoodResponses = Collections.synchronizedList(new ArrayList<ServerInfoResponse>());
        private volatile int mResponseCount = 0;
        private int mResponsesToSend = SEARCH_RANGE;

        private AlertDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new MaterialAlertDialogBuilder(requireActivity())
                    .setMessage(R.string.server_match_progress)
                    .setCancelable(true)
                    .setOnCancelListener(dialog -> cancel(true))
                    .create();
            mProgressDialog.show();
        }

        // TODO? suppress for the executeOnExecutor() below
        @SuppressLint("WrongThread")
        @Override
        protected ServerInfoResponse doInBackground(String... params) {
            final String country = params.length > 0 ? params[0] : null; // If a country is provided, search within country

            Collection<PublicServer> servers;
            if(country != null) {
                servers = new LinkedList<PublicServer>();
                for (PublicServer server : mServers) {
                    if (country.equals(server.getCountryCode())) {
                        servers.add(server);
                    }
                }
            } else {
                servers = mServers;
            }

            // For countries with 0 servers, immediately return null.
            if(servers.size() == 0)
                return null;

            // If there are less servers than the value of our range, deal with it.
            mResponsesToSend = Math.min(SEARCH_RANGE, servers.size());

            Iterator<PublicServer> iterator = servers.iterator();
            while(iterator.hasNext() && mGoodResponses.size() < mResponsesToSend) {
                PublicServer server = iterator.next();
                new MatchServerInfoTask().executeOnExecutor(mPingExecutor, server);
            }
            try {
                synchronized (mLock) {
                    mLock.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Collections.sort(mGoodResponses, mLatencyComparator);

            if(mGoodResponses.size() > 0)
                return mGoodResponses.get(0);
            else
                return null;
        }

        @Override
        protected void onPostExecute(ServerInfoResponse response) {
            super.onPostExecute(response);
            final PublicServer publicServer = response == null ? null : (PublicServer) response.getServer();
            mProgressDialog.hide();
            if (publicServer != null) {
                new MaterialAlertDialogBuilder(requireActivity())
                        .setTitle(R.string.server_match_found)
                        .setMessage(getString(R.string.server_match_info,
                                publicServer.getName(),
                                publicServer.getHost(),
                                publicServer.getPort(),
                                response.getCurrentUsers(),
                                response.getMaximumUsers(),
                                response.getVersionString(),
                                publicServer.getCountry(),
                                response.getLatency()))
                        .setPositiveButton(R.string.connect, (dialog, which) ->
                                mConnectHandler.connectToPublicServer(publicServer))
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
            } else {
                new MaterialAlertDialogBuilder(requireActivity())
                        .setTitle(R.string.server_match_not_found)
                        .setMessage(R.string.server_match_expand_country)
                        .setPositiveButton(R.string.expand, (dialog, which) -> {
                            MatchServerTask matchTask = new MatchServerTask();
                            matchTask.execute();
                        })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
            }
        }
    }
}
