package com.tsiwebserver.controller;

import com.tsiwebserver.service.FilesStorageService;
import com.tsiwebserver.model.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@CrossOrigin({"*"})
@Slf4j
public class FilesController {
    @Autowired
    FilesStorageService storageService;

    public FilesController() {
    }

    @PostMapping({"/upload"})
    @ResponseBody
    public String uploadFiles(@RequestParam("files") MultipartFile[] files) {
        log.info("files : {}", files);
        try {
            List<String> fileNames = new ArrayList();
            Arrays.asList(files).stream().forEach((file) -> {
                if (file.getContentType().split("/")[0].equals("image") && file.getOriginalFilename() != null) {
                    this.storageService.save(file);
                    fileNames.add(file.getOriginalFilename());
                }

            });
            if (fileNames.size() == 0) {
                return "1";
            } else {
                return files.length == fileNames.size() ? "2" : "3";
            }
        } catch (Exception var3) {
            return "4";
        }
    }

    @GetMapping({"/files"})
    public ResponseEntity<List<FileInfo>> getListFiles() {
        List<FileInfo> fileInfos = (List)this.storageService.loadAll().map((path) -> {
            String filename = path.getFileName().toString();
            String url = MvcUriComponentsBuilder.fromMethodName(FilesController.class, "getFile", new Object[]{path.getFileName().toString()}).build().toString();
            return new FileInfo(filename, url);
        }).collect(Collectors.toList());
        return ResponseEntity.status(HttpStatus.OK).body(fileInfos);
    }

    @GetMapping({"/files/{filename:.+}"})
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        Resource file = this.storageService.load(filename);
        return ((BodyBuilder)ResponseEntity.ok().header("Content-Disposition", new String[]{"attachment; filename=\"" + file.getFilename() + "\""})).body(file);
    }

    @GetMapping({"/files/delete/{filename:.+}"})
    public String deleteFile(@PathVariable String filename, Model model, RedirectAttributes redirectAttributes) {
        try {
            boolean existed = this.storageService.delete(filename);
            return existed ? "Delete the file successfully: " + filename : "The file does not exist!" + filename;
        } catch (Exception var5) {
//            return "Could not delete the file: " + filename + ". Error: " + var5.getMessage();
            return "Could not delete the file: " + filename + ".";
        }
    }
}
