package com.wecloud.im.service;


import com.alibaba.fastjson.JSONObject;
import com.wecloud.im.push.huawei.android.AndroidNotification;
import com.wecloud.im.push.huawei.android.ClickAction;
import com.wecloud.im.push.huawei.message.AndroidConfig;
import com.wecloud.im.push.huawei.message.Message;
import com.wecloud.im.push.huawei.messaging.HuaweiApp;
import com.wecloud.im.push.huawei.messaging.HuaweiMessaging;
import com.wecloud.im.push.huawei.model.Urgency;
import com.wecloud.im.push.huawei.reponse.SendResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;

@Slf4j
public class HuaweiPushServiceImpl implements IHuaweiPushService {

    private HuaweiMessaging huaweiMessaging;

    public HuaweiPushServiceImpl(HuaweiApp app) {
        huaweiMessaging = HuaweiMessaging.getInstance(app);
    }

    @Override
    public void singlePush(String token, String title, String body, HashMap data) throws Exception {
        ClickAction clickAction = ClickAction.builder().setType(3).build();
        AndroidNotification androidNotification = AndroidNotification.builder()
                .setTitle(title)
                .setBody(body)
                .setClickAction(clickAction)
                .build();
        AndroidConfig androidConfig = AndroidConfig.builder()
                .setCollapseKey(-1)
                .setUrgency(Urgency.NORMAL.getValue())
                .setNotification(androidNotification)
                .build();
        Message message = Message.builder()
                .setAndroidConfig(androidConfig)
                .setData(JSONObject.toJSONString(data))
                .addToken(token)
                .build();
        SendResponse sendResponse = huaweiMessaging.sendMessage(message);
        log.info("Huawei singlePush: " + JSONObject.toJSONString(sendResponse));
        if (sendResponse == null) {
            log.error("Huawei response is null");
            return;
        }
        if (!"80000000".equals(sendResponse.getCode())) {
            log.error("Huawei business error code ={} msg={}", sendResponse.getCode(), sendResponse.getMsg());
        }
    }

    JSONObject getPushData(Integer notificationId, String title, String body) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pushType", "system");
        if (notificationId != null) {
            jsonObject.put("notificationId", notificationId + "");
        }
        if (StringUtils.isNotBlank(title)) {
            jsonObject.put("title", title);
        }
        if (StringUtils.isNotBlank(body)) {
            jsonObject.put("body", body);
        }
        return jsonObject;
    }
}
