package cn.reghao.oss.console.app.service;

import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.oss.console.app.db.repository.StoreNodeRepository;
import cn.reghao.oss.console.app.db.repository.UserNodeRepository;
import cn.reghao.oss.console.app.model.po.StoreDisk;
import cn.reghao.oss.console.app.model.po.StoreNode;
import cn.reghao.oss.console.app.model.vo.KeyValue;
import cn.reghao.oss.api.dto.StoreNodeDto;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2024-02-23 13:01:38
 */
@Service
public class StoreNodeService {
    private final StoreNodeRepository storeNodeRepository;
    private final UserNodeRepository userNodeRepository;

    public StoreNodeService(StoreNodeRepository storeNodeRepository, UserNodeRepository userNodeRepository) {
        this.storeNodeRepository = storeNodeRepository;
        this.userNodeRepository = userNodeRepository;
    }

    public void addOrUpdate(StoreNodeDto storeNodeDto) {
        String nodeAddr = storeNodeDto.getNodeAddr();
        StoreNode storeNode = storeNodeRepository.findByNodeAddr(nodeAddr);
        if (storeNode == null) {
            storeNode = new StoreNode(storeNodeDto);
            storeNodeRepository.save(storeNode);
        } else {
            List<StoreDisk> storeDisks = storeNodeDto.getDiskDtoList().stream()
                    .map(StoreDisk::new)
                    .collect(Collectors.toList());
            storeNode.setStoreDisks(storeDisks);
            storeNodeRepository.save(storeNode);
        }
    }

    public Result updateStatus() {
        return Result.success();
    }

    public Result delete(int nodeId) {
        StoreNode storeNode = storeNodeRepository.findById(nodeId);
        if (storeNode == null) {
            return Result.fail("node not exist");
        }

        int total = userNodeRepository.countByNodeId(nodeId);
        if (total > 0) {
            return Result.fail("someone uses the node");
        }

        storeNodeRepository.delete(storeNode);
        return Result.success();
    }

    public List<StoreNode> getByPage() {
        return storeNodeRepository.findAll();
    }

    public StoreNode getById(int id) {
        return storeNodeRepository.findById(id);
    }

    public List<KeyValue> getNodeKeyValues() {
        return storeNodeRepository.findAll().stream()
                .map(storeNode -> {
                    int nodeId = storeNode.getId();
                    String nodeAddr = storeNode.getNodeAddr();
                    return new KeyValue(nodeId+"", nodeAddr);
                }).collect(Collectors.toList());
    }

    public StoreNode getByNodeAddr(String nodeAddress) {
        return storeNodeRepository.findByNodeAddr(nodeAddress);
    }
}
