package net.northking.cctp.scriptcase.api.app;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.scriptcase.api.app.service.FileService;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.FileMessage;
import net.northking.cctp.scriptcase.enums.MobileError;
import net.northking.cctp.scriptcase.tools.MinioPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@Api(tags = "应用表")
@RequestMapping("/v1")
@RestController
public class AppCtrl {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(AppRestfulCtrl.class);

    @Autowired
    private FileService fileService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 上传应用（大文件）
     *
     * @param appUrl
     * @return
     */

    @ApiOperation(value = "上传大文件的应用")
    @GetMapping("/v1/file/uploadLargeApp")
    @ResponseBody
    public ResultWrapper<FileMessage> uploadLargeApp(@RequestParam(value = "appUrl") String appUrl) {
        String[] split = appUrl.split("\\.");
        if (!ScriptConstant.FILE_APK.equals(split[split.length - 1].toLowerCase())
                && !ScriptConstant.FILE_IPA.equals(split[split.length - 1].toLowerCase())
                && !ScriptConstant.FILE_HAP.equals(split[split.length - 1].toLowerCase())) {
            throw new PlatformRuntimeException(MobileError.APP_TYPE_IS_ERROR);
        }
        String suffixName = appUrl.substring(appUrl.lastIndexOf(".") + 1);
        ResultWrapper<FileMessage> wrapper = new ResultWrapper<>();
        FileMessage fileMessage;
        try {
            if (ScriptConstant.FILE_APK.equals(suffixName.toLowerCase())) {
                fileMessage = fileService.uploadAndroidLargeApp(appUrl);
            } else if (ScriptConstant.FILE_IPA.equals(suffixName.toLowerCase())) {
                fileMessage = fileService.uploadIosLargeApp(appUrl);
            } else if (ScriptConstant.FILE_HAP.equals(suffixName.toLowerCase())) {
                fileMessage = fileService.uploadHarmonyOSLargeApp(appUrl);
            } else {
                throw new PlatformRuntimeException(MobileError.APP_TYPE_IS_ERROR);
            }
        }catch (PlatformRuntimeException e) {
            throw e;
        }
        fileMessage.setTimestamp(String.valueOf(wrapper.getTimestamp()));
        String[] idToPath = MinioPathUtils.idToPath(appUrl);
        redisTemplate.opsForValue().set(ScriptConstant.ATU_MOB_APP + idToPath[1], fileMessage.getFileUrl());
        return wrapper.success(fileMessage);
    }
}
