package com.wasu.cs.widget.mediacontrol;

import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.wasu.cs.widget.mediacontrol.CircularSeekBar.OnSeekChangeListener;

import java.math.BigDecimal;
import java.util.List;

import basic.app.TvAppLike;
import cn.com.wasu.main.R;

/**
 * 音量控制条
 */
public class VolumeController extends FrameLayout implements IMediaControllerChildView<IMediaController> {
	
	private final static String VOLUME_SETTINGS = "volumeSettings";
	private final static String VOLUME_FRACTION = "fraction";
	
	private IMediaController mediaController;
	
	private CircularSeekBar volumeValue;
	private TextView volumeText;
	
	private AudioManager audioManager;
	private int maxVolume;
	private int currentVolume;
	
	private float fraction = -1f;

	public VolumeController(Context context) {
		super(context);
		init(context);
	}

	public VolumeController(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public VolumeController(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context context) {
		setId(MediaController.generateID());

		LayoutInflater.from(context).inflate(R.layout.media_controller_volume, this);
		
		volumeValue = (CircularSeekBar) findViewById(R.id.volumn_value);
		volumeText = (TextView) findViewById(R.id.volumn_text);
		
		volumeValue.setProgressColor(Color.parseColor("#ffff00"), 255);
		volumeValue.setRingBackgroundColor(Color.parseColor("#ffffff"), 80);
		
		volumeValue.setSeekBarChangeListener(new OnSeekChangeListener() {

		      @Override
		      public void onProgressChange(CircularSeekBar view, int newProgress) {
		    	  setVolume(newProgress);
		      }
		});
		
		audioManager = getAudioManger();
		maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	}
	
	private void checkFraction() {
		currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		
		float f = getContext().getSharedPreferences(VOLUME_SETTINGS, Context.MODE_PRIVATE).getFloat(VOLUME_FRACTION, -1f);
		float currentV = volumeValue.getMaxProgress() * new BigDecimal(((float) currentVolume / maxVolume)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		float savedV = volumeValue.getMaxProgress() * f;
		
		if (Math.abs(currentV - savedV) <= volumeValue.getMaxProgress() * 1.f / maxVolume) {
			fraction = f;
		}
	}
	
	private AudioManager getAudioManger() {
		return (AudioManager) TvAppLike.getContext().getSystemService(Context.AUDIO_SERVICE);
	}

	public void handleFullScreen(boolean isFullScreen) {
		if (isFullScreen) {
			if (audioManager == null) {
				audioManager = getAudioManger();
			}
			currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		//	float currentV = volumeValue.getMaxProgress() * new BigDecimal(((float) currentVolume / maxVolume)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		//	setVolume((int) currentV);
		}
	}
	
	@Override
	public boolean isAutoHide() {
		return true;
	}

	@Override
	public void onShow(IMediaController mediaController) {
		this.mediaController = mediaController;

		if (audioManager == null) {
			audioManager = getAudioManger();
		}
		audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
		
		checkFraction();
		
		if (fraction == -1f) {
			int progress = (int) (volumeValue.getMaxProgress() * new BigDecimal(((float) currentVolume / maxVolume)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
			setVolume(progress);
		} else {
			int progress = (int) (volumeValue.getMaxProgress() * fraction);
			setVolume(progress);
		}
	}

	@Override
	public void onHide(IMediaController mediaController) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onShield(KeyEvent event) {
		boolean ret = false;
		if (event.getAction() == KeyEvent.ACTION_DOWN) {

			switch (event.getKeyCode()) {
				case KeyEvent.KEYCODE_DPAD_UP:
				case KeyEvent.KEYCODE_DPAD_DOWN:
				case KeyEvent.KEYCODE_VOLUME_MUTE:
				case KeyEvent.KEYCODE_MENU:
				case KeyEvent.KEYCODE_DPAD_CENTER:
				case KeyEvent.KEYCODE_ENTER:
				case KeyEvent.KEYCODE_DPAD_LEFT:
				case KeyEvent.KEYCODE_DPAD_RIGHT:
				case KeyEvent.KEYCODE_BACK:
					break;
				case KeyEvent.KEYCODE_VOLUME_DOWN:
					volumeValue.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
					ret = true;
					break;
				case KeyEvent.KEYCODE_VOLUME_UP:
					volumeValue.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
					ret = true;
					break;
				default:
					ret = true;
					break;
				}
		}
		return ret;
	}
	
	@Override
	public void clear() {
		fraction = -1f;
		
		audioManager = null;
	}

	private void setVolume(int progress) {
		volumeValue.setProgress(progress);
		volumeText.setText(String.valueOf(progress));
		
		fraction = new BigDecimal((float) progress / volumeValue.getMaxProgress()).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		getContext().getSharedPreferences(VOLUME_SETTINGS, Context.MODE_PRIVATE).edit().putFloat(VOLUME_FRACTION, fraction).commit();
		
		if (audioManager == null) {
			audioManager = getAudioManger();
		}
		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (maxVolume * fraction), 0);

		if (mediaController != null) {
			mediaController.notifyVolumeChanged((int) (maxVolume * fraction));
		}
	}

	@Override
	public void onAdStatusChanged(int arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onError(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onInfo(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPause(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPrepareComplete(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPreparing(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProgress(int arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResume(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSeekComplete(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSeeking(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStart(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(MediaPlayer arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStop(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onWasuError(int arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onWasuPlayLimit(int arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setRelativeViews(IMediaControllerChildView<IMediaController>... views) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<IMediaControllerChildView<IMediaController>> getRelativeViews() {
		// TODO Auto-generated method stub
		return null;
	}

}
