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

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;

import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.adf.util.RuntimeUtil;
import jp.agentec.adf.util.StringUtil;
import android.media.MediaPlayer;

public class ABVMediaPlayer extends MediaPlayer{
	private final static String TAG = "ABVMediaPlayer";
	private String mSrc;
	FileInputStream fis = null;
	
	public ABVMediaPlayer() {
		super();
	}
	
	public ABVMediaPlayer(boolean isRepeat) {
		super();
		this.setLooping(isRepeat);
	}
	
	@Override
    public void setDataSource(String src) throws IOException, IllegalArgumentException, IllegalStateException {
		// MediaPlayerで/data/dataのファイルを読み込めないので一時的に読み取り可に変更する
		changeReadable(src);
		super.setDataSource(getFileDataSource(src));
	}
	
	private FileDescriptor getFileDataSource(String path) throws IOException {
		if (fis == null) {
			fis = new FileInputStream(path);
		}
		return fis.getFD();
	}
	
	@Override
	public void release() {
		super.release();
		// 読み取り不可に戻す
		changeUnReadable(mSrc);
		try {
			if (fis != null) {
				fis.close();
			}
		} catch (IOException e) {
		}
	}
	
	private void changeReadable(String src){
		if(!StringUtil.isNullOrEmpty(mSrc)){
			changeUnReadable(mSrc);
		}
		try {
			RuntimeUtil.exec("chmod 754 " + src);
			mSrc = src;
		} catch (IOException e) {
			Logger.e(TAG, "chmod error. " + src, e);
		}
	}
	
	private void changeUnReadable(String path){
		try {
			RuntimeUtil.exec("chmod 750 " + mSrc);
		} catch (IOException e) {
			Logger.e(TAG, "chmod error. " + mSrc, e);
		}
	}

	@Override
	public void start() throws IllegalStateException {
		super.start();
	}
}
