package com.sunyard.chsm.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liulu
 * @since 2024/10/22
 */
@Getter
@AllArgsConstructor
public enum KeyUsage {

    // 加密解密
    ENCRYPT_DECRYPT("encrypt_decrypt", "加密解密", 1),
    // 签名验签
    SIGN_VERIFY("sign_verify", "签名验签", 2),
    // 计算HMac
    HMAC("hmac", "计算HMac", 4),
    // 计算Mac
    MAC("mac", "计算Mac", 8),

    ;
    private final String code;
    private final String desc;
    private final int value;


    public static int getStatus(List<String> codes) {
        if (CollectionUtils.isEmpty(codes)) {
            return 0;
        }

        return codes.stream()
                .map(String::toUpperCase)
                .map(KeyUsage::valueOf)
                .mapToInt(KeyUsage::getValue)
                .reduce(0, (l, r) -> l | r);
    }

    public static List<KeyUsage> getUsage(int status) {
        if (status == 0) {
            return Collections.emptyList();
        }

        return Arrays.stream(KeyUsage.values())
                .filter(it -> hasUsage(status, it))
                .collect(Collectors.toList());
    }


    public static boolean hasUsage(int nowUsage, KeyUsage usage) {
        return (nowUsage & usage.value) >= usage.value;
    }

}
