package com.qmth.boot.api.controller;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.core.exception.ForbiddenException;
import com.qmth.boot.core.exception.NotFoundException;
import com.qmth.boot.core.exception.ParameterException;
import com.qmth.boot.core.exception.UnauthorizedException;
import com.qmth.boot.core.fss.service.FileService;
import com.qmth.boot.core.fss.store.FileStore;
import com.qmth.boot.core.fss.utils.FssUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.io.InputStreamReader;

@CrossOrigin
@Controller
@RequestMapping(FssUtils.INNER_ENDPOINT_PREFIX)
@Aac(auth = false, strict = false)
public class FssController {

    @Resource
    private FileService fileService;

    @GetMapping("/{path}")
    public ResponseEntity get(@PathVariable String path,
            @RequestParam(name = FssUtils.INNER_ENDPOINT_PARAM_BUCKET) @NotBlank String bucket,
            @RequestParam(name = FssUtils.INNER_ENDPOINT_PARAM_EXPIRE_TIME) @Min(0) Long expireTime,
            @RequestParam(name = FssUtils.INNER_ENDPOINT_PARAM_SIGNATURE) @NotBlank String signature) {
        try {
            FileStore fileStore = fileService.getFileStore(bucket);
            if (fileStore == null) {
                return new ResponseEntity("bucket not exists: " + bucket, HttpStatus.BAD_REQUEST);
            }
            if (expireTime <= 0) {
                return new ResponseEntity("expireTime is invalid", HttpStatus.BAD_REQUEST);
            }
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).body(new InputStreamReader(
                    fileStore.readServerUrl(bucket, path, expireTime, StringUtils.trimToEmpty(signature))));
        } catch (ForbiddenException e) {
            return new ResponseEntity(e.getMessage(), HttpStatus.FORBIDDEN);
        } catch (NotFoundException e1) {
            return new ResponseEntity(e1.getMessage(), HttpStatus.NOT_FOUND);
        } catch (ParameterException e2) {
            return new ResponseEntity(e2.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (UnauthorizedException e3) {
            return new ResponseEntity(e3.getMessage(), HttpStatus.UNAUTHORIZED);
        } catch (Exception e4) {
            return new ResponseEntity(e4.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
