package com.gh.gamecenter.common.base.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gh.gamecenter.common.R;


/**
 * Wrap another fragment with dialog fragment.
 */
public class BaseDialogWrapperFragment extends BaseDialogFragment {

    private Fragment mFragmentToWrap;

    public static BaseDialogWrapperFragment getInstance(Fragment fragmentToWrap) {
        BaseDialogWrapperFragment fragment = new BaseDialogWrapperFragment();
        fragment.mFragmentToWrap = fragmentToWrap;
        return fragment;
    }

    public static BaseDialogWrapperFragment getInstance(Fragment fragmentToWrap, boolean isCancelable) {
        BaseDialogWrapperFragment fragment = new BaseDialogWrapperFragment();
        fragment.mFragmentToWrap = fragmentToWrap;
        fragment.setCancelable(isCancelable);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dialog_wrapper, null);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mFragmentToWrap != null) {
            getChildFragmentManager().beginTransaction().replace(R.id.fragment_placeholder, mFragmentToWrap).commitNowAllowingStateLoss();
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        getDialog().getWindow().setGravity(Gravity.BOTTOM);
        getDialog().getWindow().setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCanceledOnTouchOutside(true);
        return dialog;
    }
}
