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.domain.sys.User;
import com.microservices.wiki.domain.wiki.Wiki;
import com.microservices.wiki.domain.wiki.vo.WikiAllVo;
import com.microservices.wiki.domain.wiki.vo.WikiContent;
import com.microservices.wiki.domain.wiki.vo.WikiDeleteVo;
import com.microservices.wiki.domain.wiki.vo.WikiPageVo;
import com.microservices.wiki.refactoring.response.HttpClientResult;
import com.microservices.wiki.refactoring.utils.BeanCopyUtils;
import com.microservices.wiki.refactoring.utils.FastJsonUtils;
import com.microservices.wiki.service.sys.UserService;
import com.microservices.wiki.service.wiki.WikiService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

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

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

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

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

    @Value("${gitea-wiki-ssh-clone-domain}")
    private String giteaSSHDomain;

    @Value("${gitea-wiki-https-clone-domain}")
    private String giteaHttpsDomain;

    @Autowired
    private WikiService wikiService;

    @Autowired
    private UserService userService;

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

    @ApiOperation("wikiPages")
    @GetMapping("/wikiPages")
    public AjaxResult wikiPages(
            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 repo,
            @ApiParam(value = "id of the project", required = true) @RequestParam(defaultValue = "") Integer projectId) throws Exception {
        String giteaToken = wikiService.getGiteaToken(request, projectId);
        //未获取有效giteaToken时，赋值内置giteaToken
        giteaToken = giteaToken == null ? token : giteaToken;
        HttpClientResult httpClientResult = wikiService.getWikiPages(owner, repo, giteaToken);
        if (httpClientResult == null) {
            throw new ServiceException("获取wiki数据异常");
        }
        if (httpClientResult.getCode() == 200) {
            List<WikiPageVo> wikiPageVoList = wikiService.getWikiPageVoList(giteaHttpsDomain, giteaSSHDomain, owner, repo, httpClientResult);
            return new AjaxResult(httpClientResult.getCode(), "操作成功", wikiPageVoList);
        } else
            return new AjaxResult(httpClientResult.getCode(), "操作失败", httpClientResult.getContent());
    }

    @ApiOperation("getWiki")
    @GetMapping("/getWiki")
    public AjaxResult getWiki(
            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 repo,
            @ApiParam(value = "name of the wikipage", required = true) @RequestParam(defaultValue = "") String pageName,
            @ApiParam(value = "id of the project", required = true) @RequestParam(defaultValue = "") Integer projectId) throws Exception {
        String giteaToken = wikiService.getGiteaToken(request, projectId);
        //未获取有效giteaToken时，赋值内置giteaToken
        giteaToken = giteaToken == null ? token : giteaToken;
        HttpClientResult httpClientResult = wikiService.getWiki(owner, repo, pageName, giteaApiDomain+giteaApiBaseUrl, giteaToken);
        if (httpClientResult == null) {
            throw new ServiceException("获取wiki数据异常");
        }
        if (httpClientResult.getCode() != 200) {
            return new AjaxResult(httpClientResult.getCode(),"操作失败", httpClientResult.getContent());
        }
        WikiContent wikiContent = getWikiContent(httpClientResult);
        return new AjaxResult(httpClientResult.getCode(), "操作成功", wikiContent);
    }

    @ApiOperation("createWiki")
    @PostMapping("/createWiki")
    public AjaxResult createWiki(
            HttpServletRequest request, @Validated @RequestBody WikiAllVo wikiAllVo
    ) throws Exception {
        String giteaToken = wikiService.getGiteaToken(request, wikiAllVo.getProjectId());
        if (wikiService.StringExist(wikiAllVo.getTitle())){
            throw new ServiceException("wikiName不能以-开头");
        }
        logger.info("giteaToken:" + giteaToken);
        Wiki wiki = BeanCopyUtils.beanPropertiesCopy(wikiAllVo, Wiki.class);
        HttpClientResult httpClientResult = wikiService.createWiki(wiki, giteaToken, giteaApiDomain+giteaApiBaseUrl);
        if (httpClientResult == null) {
            throw new ServiceException("创建wiki数据异常");
        }
        return new AjaxResult(httpClientResult.getCode(), "", httpClientResult.getContent());
    }

    @ApiOperation("deleteWiki")
    @DeleteMapping("/deleteWiki")
    public AjaxResult deleteWiki(
            HttpServletRequest request, @Validated @RequestBody WikiDeleteVo wikiDeleteVo) throws Exception {
        String giteaToken = wikiService.getGiteaToken(request, wikiDeleteVo.getProjectId());
        logger.info("giteaToken: " + giteaToken);
        Wiki wiki = BeanCopyUtils.beanPropertiesCopy(wikiDeleteVo, Wiki.class);
        wiki.setTitle(wikiDeleteVo.getPageName());
        HttpClientResult httpClientResult = wikiService.deleteWiki(wiki, giteaToken, giteaApiDomain+giteaApiBaseUrl);
        if (httpClientResult == null) {
            throw new ServiceException("删除wiki数据异常");
        }
        return new AjaxResult(httpClientResult.getCode(), "", httpClientResult.getContent());
    }

    @ApiOperation("updateWiki")
    @RequestMapping(value = "/updateWiki", method = RequestMethod.PUT)
    public AjaxResult updateWiki(
            HttpServletRequest request, @Validated @RequestBody WikiAllVo wikiAllVo) throws Exception {
        String giteaToken = wikiService.getGiteaToken(request, wikiAllVo.getProjectId());
        HttpClientResult httpClientResult = updateWikiByVo(wikiAllVo, giteaToken);
        return new AjaxResult(httpClientResult.getCode(), "", httpClientResult.getContent());
    }








    /************************************************* private method *************************************************/
    private WikiContent getWikiContent(HttpClientResult httpClientResult) {
        WikiContent wikiContent = FastJsonUtils.toBean(httpClientResult.getContent(), WikiContent.class);
        if (wikiContent != null && wikiContent.getLast_commit() != null
                && wikiContent.getLast_commit().getAuthor() != null) {
            wikiContent.setImage_url(userService.getRemoteUserLogoByUserLogin(wikiContent.getLast_commit().getAuthor().getName()));
            User commitUser = userService.getUserByLogin(wikiContent.getLast_commit().getAuthor().getName());
            if(commitUser != null){
                wikiContent.setUserName(StringUtils.isEmpty(commitUser.getNickname()) ? commitUser.getLogin() : commitUser.getNickname());
            }
            if (!StringUtils.isBlank(wikiContent.getSimple_content())){
                wikiContent.setSimple_content(wikiContent.getSimple_content().replaceAll("/wiki/raw/api/attachments", "/api/attachments"));
            }
        }
        return wikiContent;
    }

    private HttpClientResult updateWikiByVo(WikiAllVo wikiAllVo, String giteaToken) throws Exception {
        String newTitleName = wikiService.StringToURLEncode(wikiAllVo.getTitle());
        if (!newTitleName.equals(wikiAllVo.getPageName())){
            HttpClientResult httpClientResult = wikiService.getWiki(wikiAllVo.getOwner(),
                    wikiAllVo.getRepo(),
                    newTitleName,
                    giteaApiDomain+giteaApiBaseUrl
                    , giteaToken
            );
            if(httpClientResult.getCode() == 200){
                throw new ServiceException("标题已存在");
            }
        }
        Wiki wiki = BeanCopyUtils.beanPropertiesCopy(wikiAllVo, Wiki.class);
        wiki.setName(wikiAllVo.getPageName());
        HttpClientResult httpClientResult = wikiService.updateWiki(wiki, giteaToken, giteaApiDomain+giteaApiBaseUrl);
        if (httpClientResult == null) {
            throw new ServiceException("更新wiki数据异常");
        }
        logger.info("****httpClientResult**** " + httpClientResult.getCode());
        return httpClientResult;
    }

}

