package com.gh.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gh.common.util.Utils;
import com.gh.gamecenter.listener.OnCallBackListener;

import java.lang.reflect.Field;

import de.greenrobot.event.EventBus;

/**
 * Created by LGT on 2016/9/4.
 */
public class BaseFragment extends Fragment implements OnCallBackListener {

	protected View view;

	protected boolean isDestroy;

	protected void init(int layout) {
		view = View.inflate(getActivity(), layout, null);

		//简化findViewById
		try {
			Class<?> clazz = this.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				int id = Utils.getId(field.getName());
				if (id != -1) {
					Utils.log("reflect name = " + field.getName());
					field.setAccessible(true);
					Class<?> fieldType = field.getType();
					Object injectedValue = fieldType.cast(view.findViewById(id));
					field.set(this, injectedValue);
					field.setAccessible(false);
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isDestroy = false;
		EventBus.getDefault().register(this);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
	                         @Nullable Bundle savedInstanceState) {
		if(container != null){
			container.removeView(view);
		}
		return view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		view = null;
		isDestroy = true;
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void loadDone() {

	}

	@Override
	public void loadDone(Object obj) {

	}

	@Override
	public void loadError() {

	}

	@Override
	public void loadEmpty() {

	}
}
