package io.renren.modules.generator.controller;

import com.jcraft.jsch.JSchException;
import io.renren.common.utils.FTPUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.generator.entity.ImagesEntity;
import io.renren.modules.generator.service.ImagesLogService;
import io.renren.modules.generator.service.ImagesService;
import io.renren.modules.minio.service.MinioAlgorithmService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-07-30 15:08:06
 */
@RestController
@RequestMapping("generator/images")
public class ImagesController {
    @Autowired
    private ImagesService imagesService;

    @Autowired
    private MinioAlgorithmService minioAlgorithmService;

    @Autowired
    private ImagesLogService imagesLogService;

    @Value("${harborUrl}")
    private String harborUrl;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:images:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = imagesService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{imageId}")
    @RequiresPermissions("generator:images:info")
    public R info(@PathVariable("imageId") Integer imageId) {
        ImagesEntity images = imagesService.getById(imageId);

        return R.ok().put("images", images);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:images:save")
    public R save(@RequestBody ImagesEntity images) {
        imagesService.save(images);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:images:update")
    public R update(@RequestBody ImagesEntity images) {
        imagesService.updateById(images);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:images:delete")
    public R delete(@RequestBody Integer[] imageIds) throws JSchException {
        for(Integer id:imageIds){
            ImagesEntity images = imagesService.getById(id);
            String imageName=images.getImageName();
            //执行删除docker镜像的命令
            String command="docker rmi "+harborUrl+"/library/"+imageName;
            FTPUtils.execCmd(command);

            //镜像构建日志也一并删除
            String modelId =minioAlgorithmService.findModelByName(images.getImageName()).substring(5);
            imagesLogService.delete(Integer.parseInt(modelId));
        }
        imagesService.removeByIds(Arrays.asList(imageIds));

        return R.ok();
    }

}
