package com.gensee.rtdemo.holder;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;

public abstract class BaseHolder extends Handler implements OnClickListener {
	protected View rootView;

	private final String TAG = getClass().getSimpleName();

	public BaseHolder(View rootView, Object value, Object... objects) {
		this.rootView = rootView;
		initData(value);
        initDatas(objects);
        initComp(value);
	}

	public BaseHolder(View rootView, Object value) {
		this.rootView = rootView;
		initData(value);
		initComp(value);
	}

	public BaseHolder(LayoutInflater inflater, int layoutID, Object value) {
		this(inflater.inflate(layoutID, null), value);
	}

	public void sendMessage(int what, Object object) {
		sendMessage(obtainMessage(what, object));
	}

	@Override
	final public void handleMessage(Message msg) {
		onMessage(msg.what, msg.obj, msg.getData());
	}

	public void onMessage(int what, Object object, Bundle bundle) {

	}

	protected View findViewById(int resId) {
		return rootView.findViewById(resId);
	}

	protected abstract void initData(Object value);

	protected void initDatas(Object... objects) {

	}

	protected abstract void initComp(Object value);
	
	public void layout(Bundle saveInstance){}

	protected Context getContext() {
		return getActivityFromView(rootView);
	}

	public View getRootView() {
		return rootView;
	}

	public String getString(int resId) {
		return getContext().getResources().getString(resId);
	}

	public void show(boolean isShow) {
		if (isShow) {
			if (View.VISIBLE != rootView.getVisibility()) {
				rootView.setVisibility(View.VISIBLE);
			}
		} else {
			if (View.GONE != rootView.getVisibility()) {
				rootView.setVisibility(View.GONE);
			}
		}
	}
	
    public boolean isShow()
    {
    	return rootView.getVisibility() == View.VISIBLE;
    }
    
	protected void startIntent(Class<?> activityClass, Bundle bundle) {
		Intent intent = new Intent(getContext(), activityClass);
		intent.putExtras(bundle);
		getContext().startActivity(intent);
	}

	protected void startIntent(Class<?> activityClass) {
		Intent intent = new Intent(getContext(), activityClass);
		getContext().startActivity(intent);
	}
	
	public void onSaveInstence(Bundle outState){}
	public void onRestoreInstanceState(Bundle savedInstanceState){}

	public static Activity getActivityFromView(View view) {
		Context context = view.getContext();
		while (context instanceof ContextWrapper) {
			if (context instanceof Activity) {
				return (Activity) context;
			}
			context = ((ContextWrapper) context).getBaseContext();
		}
		return null;
	}
}
