package cn.reghao.tnb.oss.store.db.repository;

import cn.reghao.jutil.jdk.web.db.Page;
import cn.reghao.tnb.oss.api.dto.ObjectInfo;
import cn.reghao.tnb.oss.store.db.mapper.DataBlockMapper;
import cn.reghao.tnb.oss.store.db.mapper.FileMetaMapper;
import cn.reghao.tnb.oss.store.model.po.DataBlock;
import cn.reghao.tnb.oss.store.model.po.FileMeta;
import cn.reghao.tnb.oss.api.dto.ObjectMeta;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

/**
 * @author reghao
 * @date 2023-05-22 16:48:40
 */
@Slf4j
@Service
public class ObjectRepository {
    private final FileMetaMapper fileMetaMapper;
    private final DataBlockMapper dataBlockMapper;

    public ObjectRepository(FileMetaMapper fileMetaMapper, DataBlockMapper dataBlockMapper) {
        this.fileMetaMapper = fileMetaMapper;
        this.dataBlockMapper = dataBlockMapper;
    }

    public void saveFileMeta(FileMeta fileMeta) {
        fileMetaMapper.save(fileMeta);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveObject(FileMeta fileMeta, List<DataBlock> list) {
        fileMetaMapper.save(fileMeta);
        dataBlockMapper.saveAll(list);
    }

    @CacheEvict(cacheNames = "oss:store:objectMeta", key = "#objectName")
    public void updateObjectScope(int scope, String objectName) {
        fileMetaMapper.updateScopeByObjectName(scope, objectName);
        log.info("evict {}", objectName);
    }

    @CacheEvict(cacheNames = "oss:store:objectMeta", key = "#fileMeta.objectName")
    public void deleteObject(FileMeta fileMeta) {
        String contentId = fileMeta.getContentId();
        List<FileMeta> list = fileMetaMapper.findByContentId(contentId);
        if (list.size() == 1) {
            DataBlock dataBlock = dataBlockMapper.findByContentId(contentId);
            String absolutePath = dataBlock.getAbsolutePath();

            deleteObject(fileMeta, dataBlock);
            FileUtils.deleteQuietly(new File(absolutePath));
        } else {
            fileMetaMapper.delete(fileMeta);
        }
    }

    @CacheEvict(cacheNames = "oss:store:objectMeta", key = "#fileMeta.objectName")
    public void updateFileMetaDeleted(FileMeta fileMeta) {
        fileMetaMapper.updateObjectDeleted(fileMeta);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteObject(FileMeta fileMeta, DataBlock dataBlock) {
        fileMetaMapper.delete(fileMeta);
        dataBlockMapper.delete(dataBlock);
    }

    public FileMeta getByObjectName(String objectName, int owner) {
        return fileMetaMapper.findByObjectName(objectName, owner);
    }

    public FileMeta getByObjectId(String objectId) {
        return fileMetaMapper.findByObjectId(objectId);
    }

    public FileMeta getFileMeta(String objectId) {
        return fileMetaMapper.findByObjectId0(objectId);
    }

    public FileMeta getBySha256sum(String sha256sum) {
        return fileMetaMapper.findBySha256sum(sha256sum);
    }

    @Cacheable(cacheNames = "oss:store:objectMeta", key = "#objectName+'-'+#owner", unless = "#result == null")
    public ObjectMeta getObjectMetaByName(String objectName, int owner) {
        log.info("cache miss {}", objectName);
        ObjectMeta objectMeta = fileMetaMapper.findObjectMetaByName(objectName, owner);
        return objectMeta;
    }

    public ObjectMeta getObjectMetaById(String objectId) {
        return fileMetaMapper.findObjectMetaById(objectId);
    }

    public int countByPid(String pid) {
        return fileMetaMapper.countByPid(pid);
    }

    public List<ObjectInfo> getObjectsByPage(String pid, int pn, int ps) {
        Page page = new Page(pn, ps);
        List<ObjectInfo> list = fileMetaMapper.findPidByPage(page, pid);
        return list;
    }

    @Deprecated
    void getObjects() {
        String bucket = "";
        String prefix = "image/i/";
        String startAfter = "image/cover/";
        startAfter = "";
        Integer maxKeys = 10;

        StringBuilder regex = new StringBuilder();
        //regex.append("^").append(prefix).append("([^/])+/?$");
        regex.append(prefix);
        List<FileMeta> list;
        if (startAfter.isBlank()) {
            list = fileMetaMapper.findAll0(bucket, maxKeys, regex.toString());
        } else {
            list = fileMetaMapper.findAll2(bucket, prefix, startAfter, maxKeys);
        }
    }
}
