package com.zhongshu.card.server.core.model.upLoadFile;

import com.zhongshu.card.client.type.oss.PlatformStoreType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PlatformFileItem {

    private String accountId;
    private PlatformStoreType platformStoreType;
    private String[] sourcePath;
    private Long versionNumber;

    private Boolean isReserveName;
    private String orgiFileName;


    public static PlatformFileItem from(String... path) {
        String accountName = path[0];
        PlatformStoreType platformStoreType = PlatformStoreType.valueOfPath(path[1]);
        String[] sourcePath = Arrays.copyOfRange(path, 2, path.length - 1);
        Long versionNumber = 1L;
        try {
            versionNumber = Long.valueOf(FilenameUtils.getBaseName(path[path.length - 1]));
        }catch (Exception e){
            e.printStackTrace();
        }
        return PlatformFileItem.builder().accountId(accountName).platformStoreType(platformStoreType).sourcePath(sourcePath).versionNumber(versionNumber).build();
    }


    /**
     * 转换为路径 , 文件路径 /a/b/file/1.jpg ; 平台路径 /00001/store/a/b/file/1.jpg
     *
     * @return
     */
    public String[] toPath(PathType pathType) {
        //文件名
        final String fileName = sourcePath[sourcePath.length - 1];
        //文件名
        final String baseName = FilenameUtils.getName(fileName);
        //扩展名
        final String extName = FilenameUtils.getExtension(fileName);
        //新的文件名,如果没有扩展名则为空字符串，有则使用原文件的扩展名
        String newFileName = String.format("%s%s", getVersionNumber(), extName == null ? "" : "." + extName);
        if (isReserveName != null && isReserveName && StringUtils.isNotEmpty(orgiFileName)) {
            newFileName = orgiFileName;
        }
        String finalNewFileName = newFileName;
        List<String> paths = new ArrayList<>() {{
            if (pathType == PathType.OSS) {
                add(getAccountId());
                add(getPlatformStoreType().getPath());
                addAll(List.of(Arrays.copyOfRange(sourcePath, 0, sourcePath.length - 1)));
                add(baseName);
                add(finalNewFileName);
            } else if (pathType == PathType.File) {
                addAll(List.of(Arrays.copyOfRange(sourcePath, 0, sourcePath.length - 1)));
                add(baseName);
                add(finalNewFileName);
            }
        }};
        return paths.toArray(String[]::new);
    }


    public static enum PathType {
        OSS,//对象存储
        File //平台
    }

}
