package com.mobify.astro.dialogs;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public class ViewFragment extends Fragment {
    private DialogLayout containerView;
    private View contentView;

    public ViewFragment() { }

    public View getContentView() {
        return contentView;
    }

    public void setContentView(@NonNull View contentView) {
        this.contentView = contentView;

        contentView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));

        if (containerView != null) {
            containerView.removeAllViews();
            containerView.addView(contentView);
        }
    }

    // Forces the fragment to re-render its main view
    // This is needed when changing the fragment view after the fragment
    // has already been added
    public void refresh() {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.detach(this).attach(this).commit();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (contentView == null) {
            // Don't show a dialog with no content
            return null;
        }
        containerView = new DialogLayout(inflater.getContext());
        containerView.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));

        if (contentView.getParent() != containerView) {
            ViewGroup parent = (ViewGroup) contentView.getParent();

            if (parent != null) {
                parent.removeView(contentView);
            }

            containerView.addView(contentView);
        }

        return containerView;
    }
}
