package com.castlabs.sdk.demos;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.castlabs.android.subtitles.SubtitlesPreviewView;

import java.util.Map;

public class SettingsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getFragmentManager().beginTransaction().replace(android.R.id.content,
				new SubtitleStylesPreferenceFragment()).commit();
	}

	public static class SubtitleStylesPreferenceFragment extends PreferenceFragment {

		private SubtitlesPreviewView previewView;
		private SharedPreferences.OnSharedPreferenceChangeListener sharedPreferencesListener =
				new SharedPreferences.OnSharedPreferenceChangeListener() {
					@Override
					public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
						updateSummary(key);
						updatePreview(sharedPreferences);
					}
				};


		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			addPreferencesFromResource(R.xml.prefs_subtitle_style);
			getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(
					sharedPreferencesListener);
			for (Map.Entry<String, ?> entry : getPreferenceManager().getSharedPreferences().getAll().entrySet()) {
				updateSummary(entry.getKey());
			}
		}

		@Override
		public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
								 @Nullable Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.preference_subtitles, container, false);
			previewView = (SubtitlesPreviewView) view.findViewById(R.id.preview);
			updatePreview(getPreferenceManager().getSharedPreferences());
			return view;
		}

		@Override
		public void onDestroy() {
			super.onDestroy();
			getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
					sharedPreferencesListener);
		}

		private void updateSummary(String key) {
			Preference preference = findPreference(key);
			if (preference instanceof EditTextPreference) {
				preference.setSummary(((EditTextPreference)preference).getText());
			}
		}

		private void updatePreview(SharedPreferences sharedPreferences) {
			StyleBuilder styleBuilder = new StyleBuilder(getActivity(), sharedPreferences);
			previewView.setSubtitlesStyle(styleBuilder.createSubtitleStyle());
		}
	}
}
