package com.microservices.wiki.contoller.wiki;


import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.wiki.refactoring.response.HttpClientResult;
import com.microservices.wiki.service.wiki.WikiService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "/open")
public class WikiExportController {

    @Value("${wiki-export-pdf-destPath}")
    private String destPath;

    @Value("${wkhtmltopdf-tool-path}")
    private String toPdfToolPath;

    @Value("${gitea-wiki-api-domain}")
    private String giteaApiDomain;

    @Value("${gitea-wiki-api-base-url}")
    private String  giteaApiBaseUrl;

    @Value("${gitea-wiki-token}")
    private String token;

    @Autowired
    private WikiService wikiService;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation("导出Wiki-wrapper")
    @GetMapping("/wikiExport-wrapper")
    public AjaxResult wikiExportToPdf(HttpServletResponse response,
                                      HttpServletRequest request,
                                      @ApiParam(value = "owner of the repo", required = true) @RequestParam(defaultValue = "") String owner,
                                      @ApiParam(value = "name of the repo", required = true) @RequestParam(defaultValue = "") String repoName,
                                      @ApiParam(value = "type of the file", required = true) @RequestParam(defaultValue = "") String type,
                                      @ApiParam(value = "name of the project", required = true) @RequestParam(defaultValue = "") String projectName,
                                      @ApiParam(value = "id of the project pdf|html|markdown", required = true) @RequestParam(defaultValue = "") Integer projectId) throws Exception {
        String giteaToken = wikiService.getGiteaToken(request, projectId);
        String giteaApiUrl = giteaApiDomain + giteaApiBaseUrl;
        switch (type) {
            case "pdf":
                wikiService.exportWikiToPdf(response, toPdfToolPath, owner, repoName, giteaApiUrl, destPath, giteaToken);
                break;
            case "html":
                wikiService.exportWikiToHtml(response, owner, repoName, giteaApiUrl, destPath, projectName, giteaToken);
                break;
            case "markdown":
                wikiService.exportWikiToMd(response, owner, repoName, giteaApiUrl, destPath, giteaToken);
                break;

        }
        return AjaxResult.success();
    }

    @ApiOperation("上传文件")
    @RequestMapping(value = "/uploadWiki/{owner}/{repoName}/{projectId}", method = RequestMethod.POST)
    public AjaxResult upload(
            HttpServletRequest request,
            @ApiParam(value = "owner of the repo", required = true) @PathVariable String owner,
            @ApiParam(value = "name of the repo", required = true) @PathVariable String repoName,
            @ApiParam(value = "id of the project", required = true) @PathVariable Integer projectId,
            @ApiParam(value = "The file to upload", required = true) @RequestPart MultipartFile multipartFile){
        String fileName = validateAndGetFileName(multipartFile);
        String giteaToken = wikiService.getGiteaToken(request, projectId);
        logger.info("giteaToken:" + giteaToken);
        if (wikiService.StringExist(fileName)){
            throw new ServiceException("wikiName不能以-开头");
        }
        HttpClientResult httpClientResult = wikiService.createWikiByUploadFile(giteaApiDomain, giteaApiBaseUrl, owner, repoName, multipartFile, fileName, giteaToken);
        return new AjaxResult(httpClientResult.getCode(), "", httpClientResult.getContent());
    }





    /************************************************* private method *************************************************/
    private String validateAndGetFileName(MultipartFile multipartFile) {
        if(multipartFile.isEmpty()){
            throw new ServiceException("错误参数:multipartFile,错误提示:不能为空");
        }
        String fileName = multipartFile.getOriginalFilename();
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new RuntimeException("上传的文件名为空");
        }
        return fileName;
    }
}
