package com.ffii.core.common.file.web;

import java.util.Map;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.ffii.core.common.file.service.FileService;
import com.ffii.core.exception.NotFoundException;
import com.ffii.core.response.RecordsRes;

/** @author Fung */
@RestController
@RequestMapping("/protected/file")
public class FileController {

  private FileService service;

  public FileController(FileService service) {
    this.service = service;
  }

  @GetMapping("/{refType}/{refId}")
  public RecordsRes<Map<String, Object>> list(@PathVariable String refType, @PathVariable int refId) {
    return new RecordsRes<>(service.list(refType, refId));
  }

  // #App delete
  @DeleteMapping("/{id}/{skey}")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void delete(@PathVariable int id, @PathVariable String skey) {
    if (!service.delete(id, skey)) {
      throw new NotFoundException();
    }
  }

  // #App updateFileInfo
  @PatchMapping("/{id}/{skey}")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void updateFileInfo(@PathVariable int id, @PathVariable String skey,
      @RequestBody @Valid UpdateFileInfoReq req) {
    service.updateFileInfo(id, skey, req);
  }

  public static class UpdateFileInfoReq {
    @NotBlank
    private String filename;

    private String remarks;

    public String getRemarks() {
      return remarks;
    }

    public void setRemarks(String remarks) {
      this.remarks = remarks;
    }

    public String getFilename() {
      return filename;
    }

    public void setFilename(String filename) {
      this.filename = filename;
    }

  }
}
