package com.imdroid.sideslope.service;

import com.imdroid.common.util.ThreadManager;
import com.imdroid.secapi.dto.GnssSingleData;
import com.imdroid.secapi.dto.GnssSingleDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class GnssSingleBufferServiceImpl implements GnssSingleBufferService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final List<GnssSingleData> buffer = new ArrayList<>();

    // BUFFER_SIZE 暂定此大小
    private static final int BUFFER_SIZE = 1024;
    // 资源锁
    private final Object lock = new Object();

    @Autowired
    private GnssSingleDataMapper gnssSingleDataMapper;

    @Override
    public void addData(GnssSingleData data) {
        if (data == null) {
            return;
        }
        synchronized (lock) {
            buffer.add(data);
            if (buffer.size() >= BUFFER_SIZE) {
                // 溢出时直接保存
                flush();
            }
        }
    }

    @Override
    public void flush() {
        synchronized (lock) {
            if (buffer.isEmpty()) {
                return;
            }

            try {
                List<GnssSingleData> batchList = new ArrayList<>(buffer);
                buffer.clear();

                // 数据库操作异步执行，不阻塞主线程
                ThreadManager.getSingleThreadPool("gnss-single-save").submit(() -> {
                    try {
                        saveBatch(batchList);
                        logger.debug("批量插入{}条数据成功", batchList.size());
                    } catch (Exception e) {
                        logger.error("批量插入数据失败", e);
                    }
                });

            } catch (Exception e) {
                logger.error("线程创建失败", e);
                throw e;
            }
        }
    }

    private void saveBatch(List<GnssSingleData> dataList) {
        for (GnssSingleData data : dataList) {
            gnssSingleDataMapper.insert(data);
        }
    }

    @Override
    public void clear() {
        synchronized (lock) {
            buffer.clear();
        }
    }

    @Override
    public int getBufferSize() {
        synchronized(lock) {
            return buffer.size();
        }
    }
}
