package com.genlot.ninglottery.base;

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

import com.genlot.ninglottery.widget.Diaolog.LoadingDialog;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {
    public FragmentActivity activity;
    private Unbinder mBinder;
    private LoadingDialog mLoadingDialog;

    /**
     * 设置布局layout
     *
     * @return 布局文件id
     */
    public abstract @LayoutRes
    int getLayoutResId();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View parentView = inflater.inflate(getLayoutResId(), container, false);
        activity = getActivity();
        return parentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinder = ButterKnife.bind(this, view);
        mLoadingDialog = new LoadingDialog(getActivity());
        onCreateViewFinished(savedInstanceState);
    }

    public abstract void onCreateViewFinished(Bundle state);


    private boolean isMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    public void showLoading() {
        if (isMainThread()) {
            mLoadingDialog.show();
        } else {
            activity.runOnUiThread(() -> mLoadingDialog.show());
        }
    }

    public void showLoading(String msg) {
        if (isMainThread()) {
            mLoadingDialog.show(msg);
        } else {
            activity.runOnUiThread(() -> mLoadingDialog.show(msg));
        }
    }

    public void dismissLoading() {
        if (mLoadingDialog != null) {
            if (isMainThread()) {
                mLoadingDialog.close();
            } else {
                activity.runOnUiThread(() -> mLoadingDialog.close());
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBinder.unbind();
        dismissLoading();
        activity = null;
    }


}
