package com.fs.company.cache.impl;

import com.fs.company.cache.ICompanyTagCacheService;
import com.fs.company.domain.CompanyTag;
import com.fs.company.service.ICompanyTagService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class CompanyTagCacheServiceImpl implements ICompanyTagCacheService {

    @Autowired
    private ICompanyTagService companyTagService;
    private static final Cache<TagConbKey,String> COMPANY_TAG_CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();

    private static final Cache<Long,Map<Long, CompanyTag>> COMPANY_USER_TAG_CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();


    @Data
    static class TagConbKey implements Serializable {
        private Long userId;
        private Long companyUserId;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            TagConbKey that = (TagConbKey) o;
            return Objects.equals(userId, that.userId) && Objects.equals(companyUserId, that.companyUserId);
        }

        @Override
        public int hashCode() {
            return Objects.hash(userId, companyUserId);
        }
    }
    @Override
    public String findUserTagByUserId(Long userId,Long companyUserId) {
        TagConbKey tagConbKey = new TagConbKey();
        tagConbKey.setUserId(userId);
        tagConbKey.setCompanyUserId(companyUserId);
        return COMPANY_TAG_CACHE.get(tagConbKey,e->
                companyTagService.findUserTagByUserId(tagConbKey.getUserId(),tagConbKey.getCompanyUserId()));
    }

    @Override
    public Map<Long, CompanyTag> queryAllTagMap() {
        return COMPANY_USER_TAG_CACHE.get(0L, e-> companyTagService.queryAllTagMap());
    }
}
