package xn.xxp.home.auth.fragment;

import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.hikvision.dmb.SwingCardCallback;
import com.hikvision.dmb.util.InfoUtilApi;

import core.ui.fragment.RcBaseFragment;
import http.client.ApiRepository;
import xn.xxp.databinding.FragmentAuthCardBinding;
import xn.xxp.home.auth.AuthType;
import xn.xxp.home.auth.ChoiceAuthActivity;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.LabConfig;

public class CardAuthFragment extends RcBaseFragment<FragmentAuthCardBinding> {
    private LabConfig labConfig;

    private final SwingCardCallback.Stub swingCardCallback = new SwingCardCallback.Stub() {
        @Override
        public void getInfo(String content) throws RemoteException {
            if (!TextUtils.isEmpty(content)) {
                if (content.contains(":")) {
                    String[] contentArray = content.split(":", -1);
                    if (contentArray.length > 1) {
                        String card = contentArray[1];
                        addDisposable(ApiRepository.INSTANCE.authCard(String.valueOf(labConfig.getLabId()), card).subscribe(userVo -> {
                            ChoiceAuthActivity fourChoiceAuthActivity = (ChoiceAuthActivity) CardAuthFragment.this.requireActivity();
                            fourChoiceAuthActivity.authSuccess(AuthType.CARD, userVo);
                        }, throwable -> {
                            dismissLoading();
                            showNetError(throwable);
                            LogUtils.e(Log.getStackTraceString(throwable));
                        }));
                    }
                }
            }
        }
    };

    @NonNull
    @Override
    protected FragmentAuthCardBinding createViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return FragmentAuthCardBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
        InfoUtilApi.swingCard(swingCardCallback);
    }

    @Override
    public void onDestroy() {
        InfoUtilApi.unregisterSwingCard(swingCardCallback);
        super.onDestroy();
    }
}
