package com.mjlogin.util.sms;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.StringUtil;

public class SMSThread {

	private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>());

	public static boolean sendCode(String phone) {

		String sendkey = RedisKey.VERIFICATION_CODE_SEND + phone;
		String codekey = RedisKey.VERIFICATION_CODE + phone;

		try {

			if (!Redis.use().exists(sendkey) && !Redis.use().exists(codekey)) {

				Redis.use().set(sendkey, phone);
				Redis.use().expire(sendkey, 120);

				threadPool.execute(new SendTask(phone));

				return true;
			}
		} finally {

		}

		return false;
	}

	private static final class SendTask implements Runnable {

		private final String phone;

		public SendTask(String phone) {
			this.phone = phone;
		}

		public void run() {
			try {

				String code = SMSVerification.send(phone);
				if (StringUtil.isNotEmpty(code)) {

					String key = RedisKey.VERIFICATION_CODE + phone;
					Redis.use().set(key, code);
					Redis.use().expire(key, 120);
				}

				String sendkey = RedisKey.VERIFICATION_CODE_SEND + phone;
				Redis.use().del(sendkey);
			} catch (Exception e) {

			}
		}
	}
}
