package fr.android.pointspermis.settings;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import fr.android.pointspermis.MainActivity;
import fr.android.pointspermis.R;

/**
 * Created by vins on 27/01/15.
 */
public class DossierDialogPreference extends DialogPreference {

    private final DossierDialogPreference me = this;
    private final Context context;

    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;

    private String dossier1, dossier2, dossier3;
    private EditText editTextDossier1, editTextDossier2, editTextDossier3;


    public DossierDialogPreference(Context context, AttributeSet attrs) {

        super(context,attrs);
        this.context = context;

        prefs = context.getSharedPreferences("fr.android.pointspermis", Context.MODE_PRIVATE);
        editor = prefs.edit();

        // Try to get old saved values
        dossier1 = prefs.getString(ConfigActivity.DOSSIER1_KEY, "");
        dossier2 = prefs.getString(ConfigActivity.DOSSIER2_KEY, "");
        dossier3 = prefs.getString(ConfigActivity.DOSSIER3_KEY, "");

        // Update summary
        updateSummary();

        // Default saving behaviour => useless
        //setPersistent(true);

        // Set the custom layout
        setDialogLayoutResource(R.layout.dossier_dialog);
    }

    public void updateSummary() {
        setSummary(dossier1 + "     " + dossier2 + "   " + dossier3);
    }

    public String getDossier1() {
        return dossier1;
    }

    public String getDossier2() {
        return dossier2;
    }

    public String getDossier3() {
        return dossier3;
    }

    @Override
    protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {

        builder.setTitle(R.string.pref_title_dossier);
        builder.setPositiveButton(R.string.action_valid, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface di, int i) {

                // Get parameters
                dossier1 = editTextDossier1.getText().toString();
                dossier2 = editTextDossier2.getText().toString();
                dossier3 = editTextDossier3.getText().toString();

                // Update summary
                updateSummary();

                // Save parameters
                editor.putString(ConfigActivity.DOSSIER1_KEY, dossier1);
                editor.putString(ConfigActivity.DOSSIER2_KEY, dossier2);
                editor.putString(ConfigActivity.DOSSIER3_KEY, dossier3);
                editor.putString(ConfigActivity.DOSSIER_KEY,
                        dossier1 + " " + dossier2 + " " + dossier3);
                editor.commit();

                // Trigger the onPreferenceChange event
                getOnPreferenceChangeListener().onPreferenceChange(me, "");

                di.dismiss();
            }
        });
        builder.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface di, int i) {
                di.cancel();
            }
        });

        super.onPrepareDialogBuilder(builder);
    }

    @Override
    protected void onBindDialogView(View view) {

        // Trigger the onPreferenceChange event
        getOnPreferenceChangeListener().onPreferenceChange(me, "");

        /** Set fixed EditText width, keyboard behaviour on focus and previous values ! **/

        editTextDossier1 = (EditText)view.findViewById(R.id.editTextDossier1);
        editTextDossier1.setMinWidth(editTextDossier1.getWidth());
        editTextDossier1.setMaxWidth(editTextDossier1.getWidth());
        editTextDossier1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    setImeVisibility(v, editTextDossier1, true);
                }/* else {
                    setImeVisibility(v, editTextDossier1, false);
                }*/
            }
        });
        editTextDossier1.setText(dossier1);

        editTextDossier2 = (EditText)view.findViewById(R.id.editTextDossier2);
        editTextDossier2.setMinWidth(editTextDossier2.getWidth());
        editTextDossier2.setMaxWidth(editTextDossier2.getWidth());
        editTextDossier2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    setImeVisibility(v, editTextDossier2, true);
                }/* else {
                    setImeVisibility(v, editTextDossier2, false);
                }*/
            }
        });
        editTextDossier2.setText(dossier2);

        editTextDossier3 = (EditText)view.findViewById(R.id.editTextDossier3);
        editTextDossier3.setMinWidth(editTextDossier3.getWidth());
        editTextDossier3.setMaxWidth(editTextDossier3.getWidth());
        editTextDossier3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    setImeVisibility(v, editTextDossier3, true);
                }/* else {
                    setImeVisibility(v, editTextDossier3, false);
                }*/
            }
        });
        editTextDossier3.setText(dossier3);

        super.onBindDialogView(view);
    }

    // Nice method to show/hide the virtual keyboard, extracted from the Google's 4.1 source code
    private void setImeVisibility(View v, final EditText editText, final boolean visible) {

        Runnable mShowImeRunnable = new Runnable() {
            public void run() {
                InputMethodManager imm = (InputMethodManager) getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);

                if (imm != null) {
                    imm.showSoftInput(editText, 0);
                }
            }
        };

        if (visible) {
            v.post(mShowImeRunnable);
        } else {
            v.removeCallbacks(mShowImeRunnable);
            InputMethodManager imm = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);

            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
}
