package cn.reghao.oss.store.service;

import cn.reghao.oss.storeapi.dto.ObjectChannel;
import cn.reghao.oss.storeapi.dto.StoreProperties;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2024-03-08 09:20:27
 */
@Service
public class StoreLocalService {
    private StoreProperties storeProperties;
    private final Map<String, ObjectChannel> prefixMap = new HashMap<>();
    private final Map<String, ObjectChannel> channelIdMap = new HashMap<>();

    public void initChannels(StoreProperties storeProperties, List<ObjectChannel> list) {
        this.storeProperties = storeProperties;
        for (ObjectChannel channel : list) {
            int createBy = channel.getCreateBy();

            String prefix = channel.getPrefix();
            Integer channelId = channel.getChannelId();
            prefixMap.put(createBy + "-" + prefix, channel);
            channelIdMap.put(createBy + "-" + channelId, channel);
        }
    }

    public void updateStoreProperties(StoreProperties storeProperties) {
        this.storeProperties = storeProperties;
    }

    public StoreProperties getStoreProperties() {
        return storeProperties;
    }

    public String getDomain() {
        return storeProperties != null ? storeProperties.getDomain() : null;
    }

    public String getReferer() {
        return storeProperties != null ? storeProperties.getReferer() : null;
    }

    public String getSecretKey() {
        return storeProperties != null ? storeProperties.getSecretKey() : null;
    }

    public void addObjectChannel(ObjectChannel channel) {
        int createBy = channel.getCreateBy();
        String prefix = channel.getPrefix();
        Integer channelId = channel.getChannelId();
        prefixMap.put(createBy + "-" + prefix, channel);
        channelIdMap.put(createBy + "-" + channelId, channel);
    }

    public ObjectChannel getChannelByChannelId(int loginUser, int channelId) {
        return channelIdMap.get(loginUser + "-" + channelId);
    }

    public ObjectChannel getChannelByUrl(int loginUser, String url) {
        String domain = storeProperties.getDomain();
        String objectName = url.replace("//" + domain + "/", "");
        for (String key : prefixMap.keySet()) {
            String prefix = key.split("-")[1];
            if (objectName.startsWith(prefix)) {
                return prefixMap.get(loginUser + "-" + prefix);
            }
        }

        return null;
    }

    public int getChannelIdByUrl(int loginUser, String url) {
        ObjectChannel objectChannel = getChannelByUrl(loginUser, url);
        if (objectChannel == null) {
            return -1;
        }

        return objectChannel.getChannelId();
    }

    public List<ObjectChannel> getObjectChannels() {
        return new ArrayList<>(prefixMap.values());
    }
}
