package de.tudarmstadt.informatik.hostage.ui2.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
import de.tudarmstadt.informatik.hostage.model.Profile;

/**
 * @author Alexander Brakowski
 * @created 08.02.14 23:39
 */
public class ProfileEditFragment extends PreferenceFragment implements
		SharedPreferences.OnSharedPreferenceChangeListener {

	private LayoutInflater mInflater;
	private SharedPreferences.Editor prefs;

	@Override
	public void onCreate(Bundle savedInstanceState){
		getActivity().getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		super.onCreate(savedInstanceState);

		mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View actionBarButtons = mInflater.inflate(R.layout.actionbar_donebar, new LinearLayout(getActivity()), false);
		getActivity().getActionBar().setCustomView(actionBarButtons);

		View doneButton = actionBarButtons.findViewById(R.id.action_done);
		View cancelButton = actionBarButtons.findViewById(R.id.action_cancel);

		doneButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
				ProfileManager pmanager = ProfileManager.getInstance();

				Profile profile = getProfile();

				boolean createNew = false;

				if(profile == null){
					profile = new Profile();
					createNew = true;
				} else {
					if(!profile.isEditable()){
						profile = profile.cloneProfile();
						profile.mEditable = true;
						createNew = true;
					}
				}

				profile.mLabel = prefs.getString("pref_profile_general_name", profile.mLabel);
				profile.mIconPath = prefs.getString("pref_profile_general_image", profile.mIconPath);
				profile.mText = prefs.getString("pref_profile_general_description", profile.mText);

				if(createNew){
					profile.mId = -1;
					profile.mIconId = 0;
					profile.mIconName = "";
					pmanager.addProfile(profile);
				} else {
					pmanager.persistProfile(profile);
				}

				getActivity().finish();
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getActivity().finish();
			}
		});

		Profile profile = getProfile();
		prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();

		String pname = "",
			   pimage = "",
			   pdesc = "";

		if(profile != null){
			pname = profile.mLabel;
			pimage = profile.mIconPath;
			pdesc = profile.mText;
		}

		prefs.putString("pref_profile_general_name", pname);
		prefs.putString("pref_profile_general_image", pimage);
		prefs.putString("pref_profile_general_description", pdesc);

		prefs.commit();

		addPreferencesFromResource(R.xml.profile_preferences);

		Preference pref = findPreference("pref_profile_general_image");

		assert pref != null;

		if(profile != null){
			pref.setIcon(profile.getIconDrawable());
		}

		pref.setOnPreferenceClickListener(
				new Preference.OnPreferenceClickListener() {
					@Override
					public boolean onPreferenceClick(Preference preference) {
						Intent intent = new Intent();
						intent.setType("image/*");
						intent.setAction(Intent.ACTION_GET_CONTENT);
						int PICK_IMAGE = 1;
						startActivityForResult(Intent.createChooser(intent, getString(R.string.select_icon)), PICK_IMAGE);
						return true;
					}
				}
		);

		if(profile != null){
			findPreference("pref_profile_general_name").setSummary(profile.mLabel);
			findPreference("pref_profile_general_description").setSummary(profile.mText);
		}
	}

	public Profile getProfile(){
		ProfileManager pmanager = ProfileManager.getInstance();

		Intent intent = getActivity().getIntent();
		int profile_id = intent.getIntExtra("profile_id", -1);

		if(profile_id != -1){
			return pmanager.getProfile(profile_id);
		}

		return null;
	}

	@Override
	public void onResume() {
		super.onResume();
		getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}

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

	/**
	 * Called when a shared preference is changed, added, or removed. This
	 * may be called even if a preference is set to its existing value.
	 *
	 * <p>This callback will be run on your main thread.
	 *
	 * @param sharedPreferences The {@link android.content.SharedPreferences} that received
	 *                          the change.
	 * @param key               The key of the preference that was changed, added, or
	 */
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		Preference p = findPreference(key);

		if(p instanceof EditTextPreference){
			p.setSummary(sharedPreferences.getString(key, ""));
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

		if(resultCode == Activity.RESULT_OK){
			Uri selectedImage = imageReturnedIntent.getData();
			String[] filePathColumn = {MediaStore.Images.Media.DATA};

			assert selectedImage != null;

			Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);

			assert cursor != null;
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();

			Preference pref = findPreference("pref_profile_general_image");

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.ARGB_8888;
			Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

			assert pref != null;
			pref.setIcon(new BitmapDrawable(getResources(), bitmap));

			prefs.putString("pref_profile_general_image", filePath);
			prefs.commit();
		}
	}
}
