package com.bcxin.wps.service;

import cn.wps.solution.weboffice.provider.v3.exception.FileNotExist;
import cn.wps.solution.weboffice.provider.v3.exception.UserNotExist;
import cn.wps.solution.weboffice.provider.v3.model.FileInfo;
import cn.wps.solution.weboffice.provider.v3.model.FileUploadSinglePhase;
import cn.wps.solution.weboffice.provider.v3.service.SinglePhaseFileStorageService;
import com.bcxin.wps.entity.File;
import com.bcxin.wps.repository.FileRepository;
import com.bcxin.wps.entity.User;
import com.bcxin.wps.repository.StorageRepository;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Optional;

@Service
public class SinglePhaseFileStorageServiceImpl implements SinglePhaseFileStorageService {
    @Autowired
    private FileRepository fileRepository;

    @Autowired
    private StorageRepository storageRepository;

    @Autowired
    private PreviewServiceImpl previewService;

    @Override
    @SneakyThrows
    public FileInfo uploadFile(FileUploadSinglePhase.Request request) {
        final User user = previewService.fetchUserByToken();
        if(user==null) {
            throw new UserNotExist();
        }
        Timestamp now = Timestamp.from(Instant.now());

        final File file = Optional.ofNullable(request)
                .map(r -> previewService.fetchFile(request.getFileId()))
                .map(f -> f.copyForNew(String.valueOf(user.getId()),request.getName(),f.getVersion()+1))
                .map(f -> fileRepository.save(f))
                .orElseThrow(FileNotExist::new);

        this.storageRepository.save(file, request.getFile().getBytes());

        return file.toFileInfo();
    }
}
