/* 
 * Copyright 2013 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software 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 copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.gui;

import de.avm.android.fritzapp.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MicVolumePreference extends DialogPreference
{
	private static final int MIN_VALUE = 50;
	private static final int MAX_VALUE = 250;
	private static final int STEP_VALUE = 50;
	
	private final String mMicVolumeFormat;
	private Integer mDefaultValue = null;
	private int mCurrentValue = 0;
	private boolean mResetToDefault = false;

	public MicVolumePreference(Context context)
	{
		this(context, null);
	}

	public MicVolumePreference(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		
		setPositiveButtonText(android.R.string.ok);
		setNegativeButtonText(null);
		setDialogLayoutResource(R.layout.micvolume_dialog);

		mMicVolumeFormat = context.getString(R.string.pref_mic_vol_fmt);
	}
	
	@Override
    public void setDefaultValue(Object defaultValue)
    {
		super.setDefaultValue(defaultValue);

		if (defaultValue instanceof Integer)
			mDefaultValue = (Integer)defaultValue;
		else
			throw new IllegalArgumentException(
					"Arguemnt defaultValue must be an Integer");
    }

	@Override
	protected void onAttachedToHierarchy(PreferenceManager preferenceManager)
	{
		super.onAttachedToHierarchy (preferenceManager);

		String key = getKey();
		if (!TextUtils.isEmpty(key))
		{
			// show current value in summary
			int value = preferenceManager.getSharedPreferences()
					.getInt(key, mDefaultValue);
			setSummary(String.format(mMicVolumeFormat, value));
		}
	}

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

		mResetToDefault = false;
		builder.setCancelable(true)
			.setInverseBackgroundForced(true)
			.setNeutralButton(R.string.pref_mic_vol_default,
					new OnClickListener()
			{
				public void onClick(DialogInterface dialog, int which)
				{
					mResetToDefault = true;
				}
			});
	}
	
	@Override
    protected void onBindDialogView(View view)
    {
		String key = getKey();
		if (TextUtils.isEmpty(key))
			throw new IllegalStateException(
					"MicVolumePreference requires the key of an integer prefrence.");
		mCurrentValue = getPreferenceManager().getSharedPreferences()
				.getInt(key, mDefaultValue);

        final TextView valueView = (TextView)view.findViewById(R.id.Value);
        valueView.setText(String.format(mMicVolumeFormat, mCurrentValue));
        
        SeekBar seekBar = (SeekBar)view.findViewById(R.id.SeekBar);
        seekBar.setMax((MAX_VALUE - MIN_VALUE) / STEP_VALUE);
        if (mCurrentValue < MIN_VALUE)
        	seekBar.setProgress(0);
        else if (mCurrentValue > MAX_VALUE)
        	seekBar.setProgress(seekBar.getMax());
        else
            seekBar.setProgress(Math.round((float)(mCurrentValue - MIN_VALUE) /
            		(float)STEP_VALUE));
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
        {
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser)
			{
				mCurrentValue = progress * STEP_VALUE + MIN_VALUE; 
		        valueView.setText(String.format(mMicVolumeFormat, mCurrentValue));
			}

			public void onStartTrackingTouch(SeekBar seekBar)
			{
			}

			public void onStopTrackingTouch(SeekBar seekBar)
			{
			}
        });
    }
	
	@Override
	protected void onDialogClosed(boolean positiveResult)
	{
		super.onDialogClosed(positiveResult);

		SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
		if (positiveResult)
		{
			if (mCurrentValue == prefs.getInt(getKey(), mDefaultValue))
				positiveResult = false;
		}
		else if (mResetToDefault)
		{
			mCurrentValue = mDefaultValue;
		}
		
		if (positiveResult || mResetToDefault)
		{
			Editor editor = prefs.edit();
			if (mCurrentValue == mDefaultValue)
				editor.remove(getKey());
			else
				editor.putInt(getKey(), mCurrentValue);
			editor.commit();
			setSummary(String.format(mMicVolumeFormat, mCurrentValue));
		}
	}
}
