package jp.sourceforge.nicoro;

import static jp.sourceforge.nicoro.Log.LOG_TAG;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.RemoteException;

/**
 * 実行前にVideoCacheServiceにbind済みであること
 *
 */
public class CacheDeleteTask extends AsyncTask<Void, Void, Boolean> {
    private ProgressDialog mProgressDialog;

    private Activity mActivity;
    private String mVideoNumber;

    private VideoCacheServiceConnection mVideoCacheServiceConnection;

    public CacheDeleteTask(Activity activity,
            String videoNumber) {
        mActivity = activity;
        mVideoNumber = videoNumber;
    }

    @Override
    protected void onPreExecute() {
        mProgressDialog = Util.createProgressDialogLoading(
                mActivity, R.string.progress_delete_cache_one, null);
        mProgressDialog.show();
        mVideoCacheServiceConnection =
            NicoroApplication.getInstance(mActivity).getVideoCacheServiceConnection();
    }
    @Override
    protected Boolean doInBackground(Void... params) {
        IVideoCacheService videoCacheService =
            mVideoCacheServiceConnection.getIVideoCacheService();
        if (videoCacheService != null) {
            try {
                videoCacheService.deleteCache(mVideoNumber);
                return true;
            } catch (RemoteException e) {
                Log.e(LOG_TAG, e.toString(), e);
            }
        }
        return false;
    }
    /**
     * 追加処理を行いたいときはoverrideすること
     */
    @Override
    protected void onPostExecute(Boolean result) {
        // XXX dismissでIllegalArgumentExceptionのエラーレポートが出たがどういうタイミングで起きるのか？
        // →dismissする前にonDestory起きたとき？onCreateDialog使った方がいいか？
        mProgressDialog.dismiss();
        mProgressDialog = null;
        if (result) {
            String toast = mActivity.getString(R.string.toast_delete_cache_one,
                    mVideoNumber);
            Util.showInfoToast(mActivity, toast);
        } else {
            Util.showErrorToast(mActivity,
                    R.string.toast_delete_cache_one_fail);
        }
        mActivity = null;
        mVideoCacheServiceConnection = null;
    }

    public static Dialog createCacheDeleteDialog(Activity activity,
            DialogInterface.OnClickListener positiveListener) {
        return new AlertDialog.Builder(activity)
            .setMessage(R.string.confirm_delete_cache_one)
            .setCancelable(true)
            .setPositiveButton(android.R.string.yes, positiveListener)
            .setNegativeButton(android.R.string.no, null)
            .create();
    }
}