package com.backfire.doudizhu.common;


import net.yeeyo.doudizhu.feiyu.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.backfire.utils.Log;

/**
 * @author wf
 *
 */
public class LoadingProgressDialog extends AlertDialog{

	private TextView mTipsView;
	private String mTitle;
	private onDismissListener listener = null;
	
	public interface onDismissListener
	{
		public abstract void onDismiss();
	}
	
	/**
	 * @param context
	 */
	protected LoadingProgressDialog(Context context) {
		super(context);
	}
	
	private static LoadingProgressDialog mDlg = null;
	
	public static LoadingProgressDialog show(Activity context,String title){
		try {
			mDlg = new LoadingProgressDialog(context);
			mDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
			mDlg.setCancelable(false);
			mDlg.setCanceledOnTouchOutside(false);
			mDlg.mTitle = title;
			mDlg.show();
		} catch (Exception e) {
			mDlg = null;
			Log.e("LoadingProgressDialog", e);
		}
		
		return mDlg;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = LayoutInflater.from(getContext());
		View view = inflater.inflate(R.layout.loading_progress_dialog, null);
		mTipsView = (TextView) view.findViewById(R.id.loading_progress_dialog_text);
		mTipsView.setText(mTitle);
		TextPaint paint = mTipsView.getPaint();
		paint.setFakeBoldText(true);
		setContentView(view);
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(this, "loading dismiss");
		this.listener = null;
		LoadingProgressDialog.mDlg = null;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

	    	if ( null != this.listener )
	    	{
	    		Log.d(this, "loading dismiss when click back");
	    		this.listener.onDismiss();
	    		this.dismiss();
	    	}else{
	    		this.dismiss();
	    	}
	        return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}
	
	public static void dissmissDlg(){
		LoadingProgressDialog dlg = LoadingProgressDialog.getDlg();
		if (dlg != null && dlg.isShowing()) {
			dlg.dismiss();
		}
	}
	
	private static LoadingProgressDialog getDlg() {
		return mDlg;
	}
}
