package com.ycwl.basic.image.pipeline.stages;

import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
import com.ycwl.basic.image.pipeline.enums.ImageType;
import com.ycwl.basic.pipeline.annotation.StageConfig;
import com.ycwl.basic.pipeline.core.AbstractPipelineStage;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.pipeline.enums.StageOptionalMode;
import com.ycwl.basic.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * 条件旋转Stage
 * 根据图片需要旋转的角度进行旋转（便于后续水印处理）
 */
@Slf4j
@StageConfig(
    stageId = "rotate",
    optionalMode = StageOptionalMode.UNSUPPORT,
    description = "根据需要旋转图片"
)
public class ConditionalRotateStage extends AbstractPipelineStage<PhotoProcessContext> {

    @Override
    public String getName() {
        return "ConditionalRotateStage";
    }

    @Override
    protected boolean shouldExecuteByBusinessLogic(PhotoProcessContext context) {
        Integer rotation = context.getImageRotation();
        return context.getImageType() == ImageType.NORMAL_PHOTO && (rotation != null && rotation != 0);
    }

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        try {
            File currentFile = context.getCurrentFile();
            if (currentFile == null || !currentFile.exists()) {
                return StageResult.failed("当前文件不存在");
            }

            // 获取需要旋转的角度
            Integer rotation = context.getImageRotation();
            if (rotation == null || rotation == 0) {
                return StageResult.skipped("无需旋转");
            }

            File rotatedFile = context.getTempFileManager()
                    .createTempFile("rotated", ".jpg");

            // 根据实际角度进行旋转
            log.debug("旋转图片{}度: {} -> {}", rotation, currentFile.getName(), rotatedFile.getName());
            rotateByDegree(currentFile, rotatedFile, rotation);

            if (!rotatedFile.exists()) {
                return StageResult.failed("旋转后的文件未生成");
            }

            context.updateProcessedFile(rotatedFile);
            context.setRotationApplied(true);

            log.info("图片已旋转{}度", rotation);
            return StageResult.success("已旋转" + rotation + "度");

        } catch (Exception e) {
            log.error("图片旋转失败", e);
            return StageResult.failed("旋转失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据角度旋转图片
     */
    private void rotateByDegree(File input, File output, int degree) throws Exception {
        switch (degree) {
            case 90:
                ImageUtils.rotateImage90(input, output);
                break;
            case 180:
                ImageUtils.rotateImage180(input, output);
                break;
            case 270:
                ImageUtils.rotateImage270(input, output);
                break;
            default:
                throw new IllegalArgumentException("不支持的旋转角度: " + degree);
        }
    }
}
