package com.yanzuoguang.mq.dao.impl;

import com.yanzuoguang.dao.impl.BaseDaoImpl;
import com.yanzuoguang.mq.dao.QueueServerTokenDao;
import com.yanzuoguang.mq.vo.QueueServerTokenVo;
import com.yanzuoguang.util.helper.YzgTimeout;
import com.yanzuoguang.util.thread.ThreadHelper;
import com.yanzuoguang.util.vo.MapRow;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 通过Token找到所在服务器
 *
 * @author 颜佐光
 */
@Component
public class QueueServerTokenDaoImpl extends BaseDaoImpl implements QueueServerTokenDao, InitializingBean {
    private static final String QUERY_TABLE_SQL = "SHOW TABLES LIKE 'queue_servertoken'";
    private static final String CREATE_TABLE_SQL = "CREATE TABLE `queue_servertoken` (" +
            "  `serverTokenId` varchar(32) NOT NULL COMMENT '编号'," +
            "  `serverId` varchar(32) NOT NULL COMMENT '服务Id'," +
            "  `queueName` varchar(255) NOT NULL DEFAULT '' COMMENT '消息编号'," +
            "  `tokenId` varchar(255) NOT NULL DEFAULT '' COMMENT '标记Id'," +
            "  `tokenVersion` varchar(32) NOT NULL COMMENT '版本号'," +
            "  `updateDate` datetime DEFAULT NULL COMMENT '修改时间'," +
            "  PRIMARY KEY (`serverTokenId`)," +
            "  KEY `IndexNameToken` (`queueName`,`tokenId`)," +
            "  KEY `IndexServerId` (`serverId`)" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='通过Token找到所在服务器'";

    @Override
    protected void init() {
        cacheList.setClearSecond(2);

        register(QueueServerTokenVo.class);
    }

    /**
     * Invoked by a BeanFactory after it has set all bean properties supplied
     * (and satisfied BeanFactoryAware and ApplicationContextAware).
     * <p>This method allows the bean instance to perform initialization only
     * possible when all bean properties have been set and to throw an
     * exception in the event of misconfiguration.
     *
     * @throws Exception in the event of misconfiguration (such
     *                   as failure to set an essential property) or if initialization fails.
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        ThreadHelper.runThread(() -> {
            YzgTimeout.timeOut(QueueServerTokenDaoImpl.class, "消息队列处理工具类初始化", () -> {
                List<MapRow> tables = this.getDb().query(QueueServerTokenDaoImpl.class, "QUERY_TABLE_SQL", QUERY_TABLE_SQL);
                if (tables.isEmpty()) {
                    this.getDb().update(QueueServerTokenDaoImpl.class, "CREATE_TABLE_SQL", CREATE_TABLE_SQL);
                }
            });
        });
    }
}