package com.kfzs.duanduan;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kf.utils.ToastBuilder;
import com.kfzs.duanduan.bean.KFIntentKeys;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.lang.reflect.Field;

/**
 * <pre>
 *     sinlov
 *
 *     /\__/\
 *    /`    '\
 *  ≈≈≈ 0  0 ≈≈≈ Hello world!
 *    \  --  /
 *   /        \
 *  /          \
 * |            |
 *  \  ||  ||  /
 *   \_oo__oo_/≡≡≡≡≡≡≡≡o
 *
 * </pre>
 * Created by sinlov on 17/2/13.
 */
public abstract class BaseCompatFragment extends Fragment {

    private static final String STATE_SAVE_IS_HIDDEN = "Fragment:STATE:SAVE_IS_HIDDEN";

    protected final String TAG = this.getClass().getCanonicalName();

    //Fragment主要管理
    protected FragmentManager mFragmentManager;
    //Fragment的主View
    protected View mContentView;

    protected Context mContext;

    //刷新组件，直接static
    private static SwipeRefreshLayout mSwipeRefreshLayout;


    /**
     * attach fragment and init base member
     *
     * @param context context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
        mFragmentManager = getFragmentManager();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
            FragmentManager fragmentmanager = getFragmentManager();
            if(fragmentmanager != null) {
                FragmentTransaction ft = fragmentmanager.beginTransaction();
                if (isSupportHidden) {
                    ft.hide(this);
                } else {
                    ft.show(this);
                }
                ft.commitAllowingStateLoss();
            }
        }
    }

    /**
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mContentView == null) {
            initView(savedInstanceState);
        } else {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (null != parent) {
                parent.removeView(mContentView);
            }
        }
        return mContentView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(getUserVisibleHint()){
            UMConfigUtils.onVisibilityChangedToUser(true, TAG);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(getUserVisibleHint()){
            UMConfigUtils.onVisibilityChangedToUser(false, TAG);
        }
    }

    protected abstract void initView(Bundle savedInstanceState);

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
    }

    protected void setContentView(@LayoutRes int layoutResID) {
//        mContentView = LayoutInflater.from(KFZSApp.getInstance()).inflate(layoutResID, null);
        //上面句大坑，在做主题的时候搞了很久，我去！
        mContentView = LayoutInflater.from(getActivity()).inflate(layoutResID, null);
    }

    protected void setContentViewChildMode(@LayoutRes int layoutResID) {
        mContentView = LayoutInflater.from(getActivity()).inflate(layoutResID, null);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }



    /**
     * find view by id which in content view
     *
     * @param id   view id
     * @param <CV> extends {@link View}
     * @return extends view
     */
    @SuppressWarnings("unchecked")
    protected <CV extends View> CV getViewById(@IdRes int id) {
        return (CV) mContentView.findViewById(id);
    }

    /**
     * show toast by string
     *
     * @param string toast string
     */
    protected void showToast(String string) {
        G.showToast(string);
    }


    /**
     * show toast by res
     *
     * @param string string resource id
     * @param tag    {@link ToastBuilder#DEFAULT_TOAST} or other
     */
    protected void showToast(String string, int tag) {
        ToastBuilder.make(mContext, string, tag);
    }

    /**
     * show toast by res
     *
     * @param strID string resource id
     */
    protected void showToast(int strID) {
        showToast(strID, ToastBuilder.DEFAULT_TOAST_SINGLE);
    }

    /**
     * show toast by res
     *
     * @param strID string resource id
     * @param tag   {@link ToastBuilder#DEFAULT_TOAST} or other
     */
    protected void showToast(int strID, int tag) {
        ToastBuilder.make(mContext, strID, tag);
    }


    protected void skip2GameDetails(int sGameId) {
        Intent intent = new Intent(mContext, ActGameDetails.class);
        intent.putExtra(KFIntentKeys.EXTRA_GAME_ID, String.valueOf(sGameId));
        startActivity(intent);
    }

    protected void skip2Activity(Class<?> cls) {
        skip2Activity(cls, null);
    }

    protected void skip2Activity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(getActivity(), cls);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }


    /**
     * 刷新数据
     */
    public void refreshData() {

    }

    /**
     * 刷新结束
     */
    public void refreshOver() {
        if (mSwipeRefreshLayout != null
                && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

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

    /**
     * 设置刷新组件
     *
     * @param swipeRefreshLayout
     */
    public void setmSwipeRefreshLayout(SwipeRefreshLayout swipeRefreshLayout) {
        mSwipeRefreshLayout = swipeRefreshLayout;
    }

    public static SwipeRefreshLayout getmSwipeRefreshLayout() {
        return mSwipeRefreshLayout;
    }
}
