package jp.agentec.abook.abv.ui.viewer.view.action;

import java.util.Date;

import jp.agentec.abook.abv.cl.util.ContentLogUtil;
import jp.agentec.abook.abv.ui.viewer.view.ABVMediaPlayer;
import jp.agentec.adf.util.DateTimeUtil;
import android.media.MediaPlayer;

public class TapMediaPlayer extends ABVMediaPlayer implements MediaPlayer.OnCompletionListener {
	public int tapPlayerObjectLogId = -1;
	public int actionTime = 0;
	public Date resumeDate;
	private TapMediaPlayer.OnCompletionListener listener;
	private long contentId;
	
	public TapMediaPlayer(long contentId) {
		super();
		this.contentId = contentId;
	}

	public interface OnCompletionListener{
		void onCompletion(TapMediaPlayer mp);
	}

	@Override
	public void start() throws IllegalStateException {
		setOnCompletionListener(this);
		super.start();
		resumeDate = DateTimeUtil.getCurrentDate();
	}
	
	@Override
	public void stop() throws IllegalStateException {
		boolean isPlaying = isPlaying();
		super.stop();
		
		// 再生中でない場合（一時停止等）の場合ログは更新しない
		if(isPlaying){
			updtaeActionTime();
		}
	}
	
	@Override
	public void pause() throws IllegalStateException {
		super.pause();
		updtaeActionTime();
	}
	
	@Override
	public void onCompletion(MediaPlayer mp) {
		updtaeActionTime();

		if(listener != null){
			listener.onCompletion(this);
		}
	}
	
	public void setOnCompletionListener(TapMediaPlayer.OnCompletionListener listener) {
		this.listener = listener;
	}
	
	private void updtaeActionTime(){
		actionTime += (int)(DateTimeUtil.getCurrentDate().getTime() - resumeDate.getTime());
		ContentLogUtil.getInstance().updateActionTime(contentId, tapPlayerObjectLogId, actionTime);
	}
}
