package com.meeting.demo.view.sdk;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.sdk.model.conf.entity.ConfBaseInfo;
import com.meeting.demo.R;
import com.meeting.demo.adapter.ConfListItemAdapter;
import com.meeting.demo.dependency.CustomBizNotificationHandle;
import com.meeting.demo.model.ConfItemModel;
import com.meeting.demo.model.ModeType;
import com.meeting.demo.utils.DemoUtil;
import com.meeting.demo.view.DemoActivity;
import com.meeting.demo.vision.utils.ModeUtil;
import com.meeting.demo.view.base.BaseDialogFragment;
import com.meeting.demo.view.sdkconfig.ConfDetailActivity;
import com.meeting.demo.vision.dependency.CustomVisionBizNotificationHandle;
import com.huawei.hwmfoundation.HwmContext;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmfoundation.utils.route.HCActivityManager;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.model.param.CancelCycleConfParam;

import java.util.List;

public class ListMeetingFragment extends BaseDialogFragment implements ConfListItemAdapter.Listener {

    private final static String TAG = ListMeetingFragment.class.getSimpleName();

    private ConfListItemAdapter adapter;

    private View vRoot;

    private final IConfListUpdate confListUpdate = list -> {
        HCLog.i(TAG, " onConfListUpdateNotify size : " + (list == null ? 0 : list.size()));
        updateMeetingList(list);
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getDialog() != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        vRoot = inflater.inflate(R.layout.sdk_conf_list, container, false);
        initConfList();
        if (ModeUtil.getModeType(DemoUtil.getApplication()) == ModeType.VISION) {
            CustomVisionBizNotificationHandle.registerConfListChangedListener(confListUpdate);
        } else {
            CustomBizNotificationHandle.registerConfListChangedListener(confListUpdate);
        }
        vRoot.postDelayed(() -> {
            if (isDetached()) {
                HCLog.i(TAG, " isDetached ");
                return;
            }
            List<ConfBaseInfo> confList = HWMBizSdk.getBizOpenApi().getConfList();
            if (confList == null) {
                HCLog.e(TAG, " getConfList confList is invalid ");
                return;
            }
            Log.i(TAG, " getConfList size : " + confList.size());
            updateMeetingList(confList);
        }, 50L);
        return vRoot;
    }

    private void initConfList() {
        RecyclerView rvConfList = vRoot.findViewById(R.id.demo_conf_list_recyclerview);
        adapter = new ConfListItemAdapter(this);
        rvConfList.setAdapter(adapter);
        CustomLayoutManager customLayoutManager = new CustomLayoutManager(getContext());
        customLayoutManager.setSpeedRatio(0.5);
        rvConfList.setLayoutManager(customLayoutManager);
    }

    public void updateMeetingList(List<ConfBaseInfo> confList) {
        List<ConfItemModel> confListTransformed = DemoUtil.getInstance().transform(confList);
        if (adapter != null) {
            HwmContext.getInstance().runOnMainThread(() -> {
                adapter.updateConfList(confListTransformed);
                View vEmptyTip = vRoot.findViewById(R.id.demo_vmr_list_is_empty);
                if (confListTransformed == null || confListTransformed.isEmpty()) {
                    vEmptyTip.setVisibility(View.VISIBLE);
                } else {
                    vEmptyTip.setVisibility(View.GONE);
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        HCLog.i(TAG, " onDestroy ");
        if (ModeUtil.getModeType(DemoUtil.getApplication()) == ModeType.VISION) {
            CustomVisionBizNotificationHandle.removeConfListChangedListener(confListUpdate);
        } else {
            CustomBizNotificationHandle.removeConfListChangedListener(confListUpdate);
        }
        super.onDestroy();
    }

    @Override
    public void onItemClicked(ConfItemModel item) {
        HCLog.i(TAG, " onItemClicked : " + item.getConfSubject());
        Activity currentActivity = HCActivityManager.getInstance().getCurActivity();
        if (currentActivity == null) {
            currentActivity = DemoActivity.getInstance();
        }
        if (null != currentActivity) {
            Intent intent = new Intent(currentActivity, ConfDetailActivity.class);
            intent.putExtra("confid", item.getConfId());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            currentActivity.startActivity(intent);
        }
    }

    @Override
    public void onCancelConfBtnClicked(ConfItemModel item) {
        showLoading();
        if (item.isCycleConf()) {
            CancelCycleConfParam cancelCycleConfParam = new CancelCycleConfParam();
            cancelCycleConfParam.setConfId(item.getConfId());
            cancelCycleConfParam.setEndOnlineConf(true);
            HWMBizSdk.getBizOpenApi().cancelCycleConf(item.getConfId(), new HwmCallback<Integer>() {
                @Override
                public void onSuccess(Integer result) {
                    HCLog.i(TAG, " cancelCycleConf success : " + result);
                    doDismissDialogAndFragment();
                    DemoUtil.showToast("取消周期会议成功");
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG, " cancelCycleConf failed : " + retCode + " " + desc);
                    doDismissDialogAndFragment();
                    String err = ErrorMessageFactory.create(retCode);
                    if (TextUtils.isEmpty(err)) {
                        err = DemoUtil.getResContext().getString(R.string.hwmconf_cancel_fail_tip);
                    }
                    DemoUtil.showToast("取消周期会议失败：" + err);
                }
            });
        } else {
            HWMBizSdk.getBizOpenApi().cancelConf(item.getConfId(), new HwmCallback<Integer>() {
                @Override
                public void onSuccess(Integer result) {
                    HCLog.i(TAG, " cancelConf success : " + result);
                    doDismissDialogAndFragment();
                    DemoUtil.showToast("取消会议成功");
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG, " cancelConf failed : " + retCode + " " + desc);
                    doDismissDialogAndFragment();
                    String err = ErrorMessageFactory.create(retCode);
                    if (TextUtils.isEmpty(err)) {
                        err = desc;
                    }
                    DemoUtil.showToast("取消会议失败：" + err);
                }
            });
        }
    }
}
