package com.tykj.dev.device.user.cache;

import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.UnitsService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
public class UserCache {

    private Map<Integer, User> idMap;

    @Autowired
    UnitsService unitsService;

    public UserCache(List<User> userList){
        this.idMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
    }

    public User findById(Integer id) {
        User user=idMap.get(id);
        user.setUnits(unitsService.findById(user.getUnitsId()));
        return user;
    }

    public Map<Integer, User> getIdMap() {
        return idMap;
    }

    public List<User> findAll(){
        return new ArrayList<>(idMap.values());
    }

    public UserCache refresh(List<User> userList){
        this.idMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
        return this;
    }
}
