package com.rdiot.yx485.room;

import android.content.Context;
import android.content.Intent;

import androidx.lifecycle.ViewModelProvider;

import com.rdiot.yx485.base.BaseFragmentActivity;

public class RoomManageActivity extends BaseFragmentActivity {
    private final RoomListEditableFragment mEditableFragment = new RoomListEditableFragment();
    private RoomViewModel mViewModel;
    private String mHomeId;
    private boolean mChanged;
    private int mInitRoomCount = -1;

    public static void newInstance(Context context, String homeId) {
        Intent intent = RoomManageActivity.newIntent(context, homeId);
        context.startActivity(intent);
    }

    public static Intent newIntent(Context context, String homeId) {
        Intent intent = new Intent(context, RoomManageActivity.class);
        intent.putExtra("homeId", homeId);
        return intent;
    }

    @Override
    public void initTitleBar() {
        mBinding.llTitleBar.tvTitle.setText("房间管理");
        mBinding.llTitleBar.btnTitleRight.setText("编辑");
    }

    @Override
    public void initView() {
        mViewModel = new ViewModelProvider(this).get(RoomViewModel.class);
        RoomListFragment listFragment = new RoomListFragment();
        changeFragment(listFragment);
    }

    @Override
    public void initData() {
        mHomeId = getIntent().getStringExtra("homeId");
        mViewModel.getErrorMessage().observe(this, this::showMessage);
        mViewModel.getRoomList().observe(this, list -> {
            if (mInitRoomCount >= 0 && list != null && list.size() != mInitRoomCount) {
                mChanged = true;
                return;
            }

            if (list != null) {
                mInitRoomCount = list.size();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mViewModel.loadRoomList(mHomeId);
    }

    @Override
    public void onRightTextClick() {
        String text = mBinding.llTitleBar.btnTitleRight.getText().toString();
        if ("编辑".equals(text)) {
            mBinding.llTitleBar.btnTitleRight.setText("完成");
            changeFragment(mEditableFragment);
        } else {
            mBinding.llTitleBar.btnTitleRight.setText("编辑");
            goBack("");
        }
    }

    protected void createRoom(String roomId) {
        mViewModel.createRoom(mHomeId, roomId);
    }

    protected void deleteRoom(String roomId) {
        mViewModel.deleteRoom(mHomeId, roomId);
    }

    @Override
    public void onBackPressed() {
        String text = mBinding.llTitleBar.btnTitleRight.getText().toString();
        if ("完成".equals(text)) {
            mBinding.llTitleBar.btnTitleRight.setText("编辑");
            goBack("");
            return;
        }

        Intent intent = new Intent();
        intent.putExtra("changed", mChanged);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }
}
