package org.tio.sitexxx.service.service.jpush.honor.message;

import com.alibaba.fastjson.annotation.JSONField;
import com.google.common.primitives.Booleans;
import org.tio.sitexxx.service.service.jpush.huawei.util.CollectionUtils;
import org.tio.sitexxx.service.service.jpush.huawei.util.ValidatorUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-02-21 10:36
 *    desc   :
 * </pre>
 */
public class Message {
    @JSONField(name = "notification")
    private Notification notification;

    @JSONField(name = "android")
    private AndroidConfig androidConfig;

    @JSONField(name = "token")
    private List<String> token = new ArrayList<>();

    private Message(Builder builder) {
        this.notification = builder.notification;
        this.androidConfig = builder.androidConfig;

        if (!CollectionUtils.isEmpty(builder.token)) {
            this.token.addAll(builder.token);
        } else {
            this.token = null;
        }

        /** check after message is created */
        check();
    }

    /**
     * check message's parameters
     */
    public void check() {
        int count = Booleans.countTrue(
                !CollectionUtils.isEmpty(this.token)
        );

        ValidatorUtils.checkArgument(count == 1, "Exactly one of token, topic or condition must be specified");

        if (this.notification != null) {
            this.notification.check();
        }

        if (null != this.androidConfig) {
            this.androidConfig.check(this.notification);
        }
    }

    public Notification getNotification() {
        return notification;
    }

    public AndroidConfig getAndroidConfig() {
        return androidConfig;
    }

    public List<String> getToken() {
        return token;
    }

    /**
     * builder
     *
     * @return
     */
    public static Builder builder() {
        return new Builder();
    }

    /**
     * push message builder
     */
    public static class Builder {
        private Notification notification;
        private AndroidConfig androidConfig;
        private List<String> token = new ArrayList<>();

        private Builder() {
        }

        public Builder setNotification(Notification notification) {
            this.notification = notification;
            return this;
        }

        public Builder setAndroidConfig(AndroidConfig androidConfig) {
            this.androidConfig = androidConfig;
            return this;
        }

        public Builder addToken(String token) {
            this.token.add(token);
            return this;
        }

        public Builder addAllToken(List<String> tokens) {
            this.token.addAll(tokens);
            return this;
        }

        public Message build() {
            return new Message(this);
        }
    }
}
