package com.cooleshow.base.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.FrameLayout;

import com.cooleshow.base.R;
import com.cooleshow.base.presenter.view.BaseView;
import com.cooleshow.base.utils.ErrorParse;
import com.cooleshow.base.widgets.ProgressLoading;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

public abstract class BaseFragment<V extends ViewBinding> extends Fragment implements BaseView {
    protected Context mContext;
    private View rootView;
    private FrameLayout mViewStubContent;
    private ViewStub mViewStubNoData;
    private ViewStub mViewStubError;
    private ProgressLoading mLoading;
    protected V mViewBinding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container,
                                   Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_root, container, false);
        initCommonView(rootView);
        initView(rootView);
        initData();
        return rootView;
    }

    public void initCommonView(View view) {
        mViewStubContent = view.findViewById(R.id.view_stub_content);
        mViewStubNoData = view.findViewById(R.id.view_stub_nodata);
        mViewStubError = view.findViewById(R.id.view_stub_error);
        mViewBinding = getLayoutView();
        mViewStubContent.addView(mViewBinding.getRoot());
        mLoading = ProgressLoading.Companion.create(requireContext());
    }

    protected abstract V getLayoutView();

    protected abstract void initView(View rootView);

    protected abstract void initData();

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLoading != null) {
            mLoading.stopAnim();
        }
        if (mViewBinding != null) {
            mViewBinding = null;
        }
    }

    public void showLoading() {
        if (mLoading != null) {
            mLoading.showLoading();
        }
    }

    public void hideLoading() {
        if (mLoading != null) {
            mLoading.hideLoading();
        }
    }


    @Override
    public void onError(@NonNull Throwable throwable) {
        throwable.printStackTrace();
        ErrorParse.getInstance().parseError(throwable);
    }
}
