package cn.axzo.msg.center.nimpush;

import cn.axzo.basics.common.constant.enums.CodeDefinition;
import cn.axzo.im.center.api.vo.req.PushContent;
import cn.axzo.im.center.api.vo.req.PushMessageTye;
import cn.axzo.msg.center.push.PushData;
import cn.axzo.msg.center.push.PushMessage;
import cn.axzo.msg.center.service.domain.UrlConfig;
import cn.axzo.msg.center.service.domain.UrlConfigVisitor;
import cn.axzo.msg.center.service.domain.UrlConfigWalker;
import cn.axzo.msg.center.service.domain.url.AppUrl;
import org.springframework.stereotype.Service;

/**
 * @author yanglin
 */
@Service
public class NimPushService {

    public PushContent buildPushContent(PushMessage message, boolean buildPushUrl) {
        PushData pushData = message.getPushData();
        if (pushData == null || !pushData.isSwitchOn()) return null;
        PushContent content = new PushContent();
        content.setTitle(message.getPushTitle());
        content.setContent(message.getPushContent());
        content.setMessageTye(CodeDefinition
                .findByCode(PushMessageTye.class, pushData.getType())
                .orElse(null));
        content.setCustomSoundFile(pushData.getVoiceFile());
        if (buildPushUrl)
            populateUrl(content, message.getPushUrl());
        return content;
    }

    private void populateUrl(PushContent content, UrlConfig url) {
        if (url == null) return;
        UrlConfigWalker.walkDown(url, new UrlConfigVisitor() {
            @Override
            public void visitAppManagerAndroid(AppUrl android) {
                if (android.hasUrl())
                    content.setMangerAndroidPushUrl(android.getUrl());
            }

            @Override
            public void visitAppManagerIos(AppUrl ios) {
                if (ios.hasUrl())
                    content.setManagerIosPushUrl(ios.getUrl());
            }

            @Override
            public void visitAppWorkerAndroid(AppUrl android) {
                if (android.hasUrl())
                    content.setWorkerAndroidPushUrl(android.getUrl());
            }

            @Override
            public void visitAppWorkerIos(AppUrl ios) {
                if (ios.hasUrl())
                    content.setWorkerIosPushUrl(ios.getUrl());
            }
        });
    }

}