/*
 * DSBDirect
 * Copyright (C) 2019 Fynn Godau
 *
 * 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 <https://www.gnu.org/licenses/>.
 *
 * This software is not affiliated with heinekingmedia GmbH, the
 * developer of the DSB platform.
 */

package godau.fynn.dsbdirect;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TimePicker;
import humanize.Humanize;

// Thanks, https://stackoverflow.com/a/12806877

public class SettingsActivity extends Activity {

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

        // Display the fragment as the main content
        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PrefsFragment()).commit();

    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);

        super.onBackPressed();
    }

    public static class PrefsFragment extends PreferenceFragment {

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

            getPreferenceManager().setSharedPreferencesName("default");
            final SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences();

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preferences);

            // Listener to reset token
            final Preference.OnPreferenceChangeListener resetToken = new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    // Reset token
                    new Utility(getActivity()).resetToken();

                    return true;
                }
            };

            // Display value in id field
            final Preference id = findPreference("id");
            id.setSummary(sharedPreferences.getString("id", "162161"));

            // Display new value and reset token on change of id
            findPreference("id").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    preference.setSummary((CharSequence) newValue);
                    return resetToken.onPreferenceChange(preference, newValue);
                }
            });

            // Reset token on change of pass
            findPreference("pass").setOnPreferenceChangeListener(resetToken);

            // Let Set Filter button open the Set Filter popup
            findPreference("set_filter").setOnPreferenceClickListener(getOnSetFilterClickListener());

            // Let Check for updates now button Check for updates now
            findPreference("updates_check_now").setOnPreferenceClickListener(getOnCheckUpdateNowClickListener());

            // Disable parsing if API level is too low
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
                Preference parse = findPreference("parse");
                parse.setEnabled(false);
                parse.setSummary(R.string.settings_view_parse_api_too_low);
                sharedPreferences.edit().putBoolean("parse", false).apply();
            }

            // Disable polling if API level is too low
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                Preference poll = findPreference("poll");
                poll.setEnabled(false);
                poll.setSummary(R.string.settings_view_polling_api_too_low);
                sharedPreferences.edit().putBoolean("poll", false).apply();
            }


            // Gray out Delete all files now when no files are available
            final Preference clearCache = findPreference("clear_cache_now");
            final FileManager fileManager = new FileManager(getActivity());
            final int fileCount = fileManager.countFiles();

            if (fileCount <= 0) {
                clearCache.setEnabled(false);
            }

            // Delete all files when Delete all files now is pressed
            clearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    // Prompt for confirmation
                    new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.clear_cache_popup_title)
                            .setMessage(getString(R.string.clear_cache_popup_message,
                                    Humanize.pluralize(
                                            getString(R.string.one_file), "{0} " + getString(R.string.files),
                                            "{0} " + getString(R.string.files), fileCount
                                    ),
                                    Humanize.binaryPrefix(fileManager.occupiedStorage())))
                            .setNegativeButton(R.string.cancel, null)
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // Delete all files
                                    fileManager.deleteAllFiles();

                                    // There are no more files left (hopefully)
                                    clearCache.setEnabled(false);
                                }
                            })
                            .show();

                    return true;
                }
            });

            // Schedule or cancel notification when Enable notifications is toggled
            findPreference("poll").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        // Utility will check whether polling is enabled and act accordingly
                        new Utility(getActivity()).schedulePolling();
                    }

                    return true;
                }
            });

            // Show version number in About description preference summary
            findPreference("settings_about_description").setSummary(getString(R.string.settings_about_description_summary, BuildConfig.VERSION_NAME));

            // Let Write the developer an email message button enable the user to Write the developer an email message
            findPreference("settings_about_email").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Intent emailTheDev = new Intent(Intent.ACTION_VIEW);
                    emailTheDev.setData(Uri.parse(getString(R.string.email_uri, getString(R.string.email_body))));

                    startActivity(emailTheDev);

                    return true;
                }
            });

            // Request a parser to be developed button should allow users to Request a parser to be developed
            findPreference("settings_about_request_parser").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.request_parser_popup_title)
                            .setMessage(R.string.request_parser_popup_message)
                            .setNegativeButton(R.string.dont_request, null)
                            .setPositiveButton(R.string.acknowledge, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent emailTheDev = new Intent(Intent.ACTION_VIEW);
                                    emailTheDev.setData(Uri.parse(getString(R.string.parser_request_uri,
                                            getString(R.string.parser_request_body, sharedPreferences.getString("id", "…there is already a parser for the default login"),
                                                    sharedPreferences.getString("pass", "…you needn't request one")))));

                                    startActivity(emailTheDev);
                                }
                            })
                            .show();

                    return true;
                }
            });

            // Check out repository when Check out repository is selected
            findPreference("settings_about_repository").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Intent checkOutRepo = new Intent(Intent.ACTION_VIEW);
                    checkOutRepo.setData(Uri.parse(getString(R.string.uri_repository)));
                    startActivity(checkOutRepo);
                    return true;
                }
            });

            // Lead user to page where they can File an issue once they click File an issue
            findPreference("settings_about_issue").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    Intent fileAnIssue = new Intent(Intent.ACTION_VIEW);
                    fileAnIssue.setData(Uri.parse(getString(R.string.uri_issue_tracker)));
                    startActivity(fileAnIssue);
                    return true;
                }
            });
        }

        private Preference.OnPreferenceClickListener getOnSetFilterClickListener() {
            return new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {

                    // spawn layout
                    View promptView = LayoutInflater.from(getActivity()).inflate(R.layout.action_filter, null);

                    // get sharedPreferences
                    final SharedPreferences sharedPreferences1 = new Utility(getActivity()).getSharedPreferences();

                    // find fields
                    final EditText inputNumber = promptView.findViewById(R.id.input_number);
                    final EditText inputLetter = promptView.findViewById(R.id.input_letter);
                    final EditText inputName = promptView.findViewById(R.id.input_name);

                    // fill in data from sharedPreferences
                    inputNumber.setText(sharedPreferences1.getString("number", ""));
                    inputLetter.setText(sharedPreferences1.getString("letter", ""));
                    inputName.setText(sharedPreferences1.getString("name", ""));

                    AlertDialog al = new AlertDialog.Builder(getActivity())
                            .setView(promptView)
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    String number = inputNumber.getText().toString();
                                    String letter = inputLetter.getText().toString();
                                    String name = inputName.getText().toString();
                                    sharedPreferences1.edit()
                                            .putString("number", number)
                                            .putString("letter", letter)
                                            .putString("name", name)
                                            .apply();
                                }
                            })
                            .setNegativeButton(R.string.cancel, null)
                            .setCancelable(false) // user might accidentally click it away otherwise
                            .setTitle(R.string.action_filter_popup_title)
                            .setMessage(R.string.action_filter_popup_message)
                            .show();
                    return true;
                }
            };
        }

        private Preference.OnPreferenceClickListener getOnCheckUpdateNowClickListener() {
            return new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    new Utility(getActivity()).checkForUpdate(true);
                    return true;
                }
            };
        }

        private String makeTime(int hour, int minute) {
            String minuteString = String.valueOf(minute);
            String hourString = String.valueOf(hour);

            if (minuteString.length() < 2) {
                minuteString = "0" + minuteString;
            }

            if (hourString.length() < 2) {
                hourString = "0" + hourString;
            }
            return hourString + ":" + minuteString;
        }


    }
}