package com.lanyuanxiaoyao.service.info.configuration;

import com.lanyuanxiaoyao.service.configuration.entity.info.SQLLine;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * SQL记录
 *
 * @author lanyuanxiaoyao
 * @date 2023-07-11
 */
@Configuration
public class SQLLoggerProvider {
    @Bean
    public SQLLogger sqlLogger() {
        return new SQLLogger(200);
    }

    public static final class SQLLogger {
        private final int size;
        private final Queue<SQLLine> container = new ConcurrentLinkedQueue<>();

        public SQLLogger(int size) {
            this.size = size;
        }

        public void log(String sql) {
            log(new SQLLine(sql));
        }

        public void log(String sql, String comment) {
            log(new SQLLine(sql, comment));
        }

        public void log(SQLLine line) {
            if (container.size() >= size) {
                container.poll();
            }
            container.add(line);
        }

        public ImmutableList<SQLLine> getLogs() {
            return Lists.immutable.ofAll(container);
        }
    }
}
