package com.base.utils.base;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.base.utils.R;
import com.base.utils.tools.android.IntentUtil;


/**
 * 第二个页面
 * 其他Activity,用于装载fragment
 * 1.通过 bundle.getSerializable 得到需要显示的Fragment
 * 2.得到显示的Fragment之后，getMap 取得title
 */

public class ActivityOtherSecond extends BaseActivity {
    final public static String TITLE = "title";
    @SuppressLint("StaticFieldLeak")
    private static ActivityOtherSecond instance;

    /**
     * 对外暴露的方法
     */
    public static void setFragment(BaseFragment fragment) {
        if (instance != null) {
            instance.switchFragment(fragment);
        } else {
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseFragment.class.getSimpleName(), fragment);
            IntentUtil.startActivity(fragment.getContext(), ActivityOtherSecond.class, bundle);
        }
    }

    TextView titleView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        setContentView(R.layout.activity_other);
        titleView = findViewById(R.id.other_title);
        onData();
        onView();
    }

    @Override
    public void onData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            BaseFragment fragment = (BaseFragment) bundle.getSerializable(BaseFragment.class.getSimpleName());
            switchFragment(fragment);
        }

    }

    /**
     * 切换碎片
     */
    private void switchFragment(BaseFragment fragment) {
        if (fragment.getMap() != null) {
            instance.titleView.setText(fragment.getMap().get(ActivityOtherSecond.TITLE));
        }
        instance.getSupportFragmentManager().beginTransaction().replace(R.id.other_fragment_content, fragment).commit();
    }

    @Override
    public void onView() {
        findViewById(R.id.other_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }
}
