package com.eactive.httpmockserver.common.mapper;

import com.eactive.httpmockserver.client.dto.ApiRequestKeyValueDTO;
import org.mapstruct.Mapper;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Mapper(componentModel = "spring",
        unmappedTargetPolicy = ReportingPolicy.IGNORE)
public class CommonMapper {

    public String map(boolean value) {
        return value ? "Y" : "N";
    }

    public boolean map(String value) {
        if (value == null) return false;
        return value.equals("Y");
    }

    public String map(List<String> values) {
        if (values == null) return "";
        return String.join(",", values);
    }

    public List<String> toList(String value) {
        if (StringUtils.hasLength(value)) return new ArrayList<>();

        return Arrays.asList(value.split(","));
    }

    @Named("authorities")
    public List<String> authorities(Collection<? extends GrantedAuthority> grantedAuthorities) {

        return grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
    }

    public String mapKeyValue(List<ApiRequestKeyValueDTO> list) {
        if (list == null) return "";
        StringBuilder result = new StringBuilder();
        for (ApiRequestKeyValueDTO dto : list) {
            result.append(dto.toString()).append("||");
        }
        if (result.length() > 0) {
            result.setLength(result.length() - 2); // Remove the last "||"
        }
        return result.toString();
    }

    public List<ApiRequestKeyValueDTO> keyValueToList(String keyValue) {
        List<ApiRequestKeyValueDTO> list = new ArrayList<>();

        if (!StringUtils.hasLength(keyValue)) return list;

        String[] pairs = keyValue.split("\\|\\|");
        for (String pair : pairs) {
            ApiRequestKeyValueDTO dto = new ApiRequestKeyValueDTO();
            if (pair.startsWith("//")) {
                dto.setEnabled(false);
                pair = pair.substring(2);
            } else {
                dto.setEnabled(true);
            }
            String[] keyValueArray = pair.split("::");
            if (keyValueArray.length == 2) {
                dto.setKey(keyValueArray[0]);
                dto.setValue(keyValueArray[1]);
                list.add(dto);
            }
        }
        return list;
    }
}
