package app.fedilab.fedilabtube.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.FragmentActivity;
import androidx.preference.ListPreference;
import androidx.preference.MultiSelectListPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceScreen;
import androidx.preference.SeekBarPreference;
import androidx.preference.SwitchPreference;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.helper.Helper;
import es.dmoral.toasty.Toasty;

import static app.fedilab.fedilabtube.MainActivity.peertubeInformation;

/* Copyright 2020 Thomas Schneider
 *
 * This file is a part of TubeLab
 *
 * 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.
 *
 * TubeLab 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 TubeLab; if not,
 * see <http://www.gnu.org/licenses>. */

public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.main_preferences);
        createPref();
    }


    @Override
    public void onResume() {
        super.onResume();

        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        if (getActivity() != null) {
            SharedPreferences sharedpreferences = getActivity().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedpreferences.edit();

            if (key.compareTo(getString(R.string.set_video_mode_choice)) == 0) {
                ListPreference set_video_mode_choice = findPreference(getString(R.string.set_video_mode_choice));
                if (set_video_mode_choice != null) {
                    switch (set_video_mode_choice.getValue()) {
                        case "0":
                            editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_NORMAL);
                            break;
                        case "1":
                            editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_STREAMING);
                            break;
                        case "2":
                            editor.putInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_WEBVIEW);
                            break;
                    }

                }
            }
            if (key.compareTo(getString(R.string.set_video_quality_choice)) == 0) {
                ListPreference set_video_quality_choice = findPreference(getString(R.string.set_video_quality_choice));
                if (set_video_quality_choice != null) {
                    switch (set_video_quality_choice.getValue()) {
                        case "0":
                            editor.putInt(Helper.SET_QUALITY_MODE, Helper.QUALITY_HIGH);
                            break;
                        case "1":
                            editor.putInt(Helper.SET_QUALITY_MODE, Helper.QUALITY_MEDIUM);
                            break;
                        case "2":
                            editor.putInt(Helper.SET_QUALITY_MODE, Helper.QUALITY_LOW);
                            break;
                    }
                }
            }
            if (key.compareTo(getString(R.string.set_video_cache_choice)) == 0) {
                SeekBarPreference set_video_cache_choice = findPreference(getString(R.string.set_video_cache_choice));
                assert set_video_cache_choice != null;
                final int progress = set_video_cache_choice.getValue();
                set_video_cache_choice.setSummary(getActivity().getString(R.string.video_cache_value, progress * 10));
                editor.putInt(Helper.SET_VIDEO_CACHE, progress * 10);
            }
            if (key.compareTo(getString(R.string.set_video_minimize_choice)) == 0) {
                SwitchPreference set_video_minimize_choice = findPreference(getString(R.string.set_video_minimize_choice));
                assert set_video_minimize_choice != null;
                editor.putBoolean(getString(R.string.set_video_minimize_choice), set_video_minimize_choice.isChecked());
            }
            if (key.compareTo(getString(R.string.set_video_language_choice)) == 0) {
                MultiSelectListPreference set_video_language_choice = findPreference(getString(R.string.set_video_language_choice));
                assert set_video_language_choice != null;
                editor.putStringSet(getString(R.string.set_video_language_choice), set_video_language_choice.getValues());
            }
            editor.apply();
        }
    }

    private void createPref() {
        getPreferenceScreen().removeAll();
        addPreferencesFromResource(R.xml.main_preferences);
        PreferenceScreen preferenceScreen = getPreferenceScreen();
        FragmentActivity context = getActivity();
        assert context != null;
        if (preferenceScreen == null) {
            Toasty.error(getActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show();
            return;
        }

        //****** Video mode *******
        ListPreference set_video_mode_choice = findPreference(getString(R.string.set_video_mode_choice));
        List<String> array = Arrays.asList(getResources().getStringArray(R.array.settings_video_mode));
        CharSequence[] entries = array.toArray(new CharSequence[0]);
        CharSequence[] entryValues = new CharSequence[3];
        final SharedPreferences sharedpref = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
        int video_mode = sharedpref.getInt(Helper.SET_VIDEO_MODE, Helper.VIDEO_MODE_NORMAL);
        entryValues[0] = String.valueOf(Helper.VIDEO_MODE_NORMAL);
        entryValues[1] = String.valueOf(Helper.VIDEO_MODE_STREAMING);
        entryValues[2] = String.valueOf(Helper.VIDEO_MODE_WEBVIEW);
        if (set_video_mode_choice != null) {
            set_video_mode_choice.setEntries(entries);
            set_video_mode_choice.setEntryValues(entryValues);
            set_video_mode_choice.setValueIndex(video_mode);
        }

        //****** Video quality *******
        ListPreference set_video_quality_choice = findPreference(getString(R.string.set_video_quality_choice));
        List<String> arrayQuality = Arrays.asList(getResources().getStringArray(R.array.settings_video_quality));
        CharSequence[] entriesQuality = arrayQuality.toArray(new CharSequence[0]);
        CharSequence[] entryValuesQuality = new CharSequence[3];
        int video_quality = sharedpref.getInt(Helper.SET_QUALITY_MODE, Helper.QUALITY_HIGH);
        entryValuesQuality[0] = String.valueOf(Helper.QUALITY_HIGH);
        entryValuesQuality[1] = String.valueOf(Helper.QUALITY_MEDIUM);
        entryValuesQuality[2] = String.valueOf(Helper.QUALITY_LOW);
        if (set_video_quality_choice != null) {
            set_video_quality_choice.setEntries(entriesQuality);
            set_video_quality_choice.setEntryValues(entryValuesQuality);
            set_video_quality_choice.setValueIndex(video_quality);
        }
        //****** Video cache *******
        SeekBarPreference set_video_cache_choice = findPreference(getString(R.string.set_video_cache_choice));
        int video_cache = sharedpref.getInt(Helper.SET_VIDEO_CACHE, Helper.DEFAULT_VIDEO_CACHE_MB);
        assert set_video_cache_choice != null;
        set_video_cache_choice.setValue(video_cache / 10);

        boolean minimized = sharedpref.getBoolean(getString(R.string.set_video_minimize_choice), true);
        SwitchPreference set_video_minimize_choice = findPreference(getString(R.string.set_video_minimize_choice));
        assert set_video_minimize_choice != null;
        set_video_minimize_choice.setChecked(minimized);


        LinkedHashMap<String, String> languages = new LinkedHashMap<>(peertubeInformation.getLanguages());
        List<CharSequence> entriesLanguages = new ArrayList<>();
        List<CharSequence> valuesLanguages = new ArrayList<>();
        Iterator<Map.Entry<String, String>> it = languages.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            entriesLanguages.add(pair.getValue());
            valuesLanguages.add(pair.getKey());
            it.remove();
        }
        MultiSelectListPreference set_video_language_choice = findPreference(getString(R.string.set_video_language_choice));
        Set<String> selection = sharedpref.getStringSet(getString(R.string.set_video_language_choice), null);
        assert set_video_language_choice != null;
        set_video_language_choice.setEntries(entriesLanguages.toArray(new CharSequence[]{}));
        set_video_language_choice.setEntryValues(valuesLanguages.toArray(new CharSequence[]{}));

        if (selection != null) {
            set_video_language_choice.setValues(selection);
        }
    }

}
