package org.springblade.modules.resource.template;

import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.sms.SmsTemplate;
import org.springblade.core.sms.model.SmsCode;
import org.springblade.core.sms.model.SmsData;
import org.springblade.core.sms.model.SmsResponse;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.resource.builder.sms.SmsBuilder;
import org.springblade.modules.resource.builder.sms.client.HwClient;
import java.time.Duration;
import java.util.Collection;

/**
 * @author: lianghanqiang
 * @description:
 * @since: 8/25/21 -- 3:55 PM
 */
public class HwSmsTemplate implements SmsTemplate {

	private HwClient hwClient;
	private BladeRedis bladeRedis;


	public HwSmsTemplate(HwClient hwClient, BladeRedis bladeRedis) {
		this.bladeRedis = bladeRedis;
		this.hwClient = hwClient;
	}

	@Override
	public SmsResponse sendMessage(SmsData smsData, Collection<String> phones) {
		return hwClient.sendMessage(phones,smsData);
	}

	@Override
	public SmsCode sendValidate(SmsData smsData, String phone) {
		String ex = smsData.getParams().get(SmsBuilder.PARAMS_EX);
		SmsCode smsCode = new SmsCode();
		smsCode.setPhone(phone);
		boolean temp = this.sendSingle(smsData, phone);
		if (temp && StringUtil.isNotBlank(smsData.getKey())) {
			String id = StringUtil.randomUUID();
			String value = smsData.getParams().get(smsData.getKey());
			this.bladeRedis.setEx(this.cacheKey(phone, id), value, Duration.ofMinutes(StringUtil.isBlank(ex)? Long.parseLong(ex) :30L));
			smsCode.setId(id).setValue(value);
		} else {
			smsCode.setSuccess(Boolean.FALSE);
		}
		return smsCode;
	}

	@Override
	public boolean validateMessage(SmsCode smsCode) {
		String id = smsCode.getId();
		String value = smsCode.getValue();
		String phone = smsCode.getPhone();
		String cache = this.bladeRedis.get(this.cacheKey(phone, id));
		if (StringUtil.isNotBlank(value) && StringUtil.equalsIgnoreCase(cache, value)) {
			this.bladeRedis.del(this.cacheKey(phone, id));
			return true;
		} else {
			return false;
		}
	}
}
