package com.bcxin.wps.controllers;

import cn.wps.solution.weboffice.provider.v3.exception.FileNotExist;
import com.bcxin.wps.entity.File;
import com.bcxin.wps.entity.FileId;
import com.bcxin.wps.repository.FileRepository;
import com.bcxin.wps.repository.StorageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Optional;

@Controller
@RequestMapping(value = "/console")
public class ConsoleController {
    private final static Logger logger = LoggerFactory.getLogger(ConsoleController.class);
    @Autowired
    private StorageRepository storageRepository;

    @Autowired
    private FileRepository fileRepository;

    @GetMapping(value = "/download/{file_id}/{version}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public @ResponseBody byte[] download(@PathVariable("file_id") String fileId,
                                         @PathVariable("version") int version) {
        return storageRepository.findByFileId(FileId.builder().id(fileId).version(version).build());
    }

    File fetchFile(String fileId) {
        return Optional.ofNullable(fileId)
                .map(fileRepository::findByIdId)
                .map(Collection::stream)
                .flatMap(s -> s.max(Comparator.comparingInt(f -> f.getVersion())))
                .orElseThrow(FileNotExist::new);
    }

    @PutMapping(value = "/upload/{file_id}")
    public @ResponseBody String upload(@PathVariable("file_id") String fileId, @RequestBody byte[] content) throws Exception {
        logger.error("ConsoleController.upload:fileId={};size={};",fileId, content == null ? "0" : content.length);
        // ATTENTION a dirty version is written into storage
        /*
        Optional<FileId> fid =
                Optional.ofNullable(fileId)
                        .map(s -> fetchFile(s))
                        .map(f -> FileId.builder().id(f.getId()).version(f.getVersion() + 1).build());
         */

        File newVersionFile = fetchFile(fileId);

        if (newVersionFile == null) {
            throw new FileNotExist();
        } else {
            newVersionFile.setVersion(newVersionFile.getVersion() + 1);
            storageRepository.save(newVersionFile, content);
        }

        return "ok";
    }
}
