package common.service.impl;

import common.repository.ConfigParamRepository;
import common.service.ConfigParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class ConfigParamServiceImpl implements ConfigParamService {

    private static Map<String, String> simpleCache = new HashMap<>();

    @Autowired
    private ConfigParamRepository configParamRepository;

    @Override
    public boolean checkMastPassWord(String password) {

        String masterPassPrefix = "manage_master_password";
        String timeflag = "_timeflag";

        String mastPassParam = simpleCache.get(masterPassPrefix);

        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();

        if (StringUtils.isEmpty(mastPassParam)) {
            mastPassParam = putMasterPass(masterPassPrefix, timeflag, localTime);
        } else {

            String timeFlag = simpleCache.get(masterPassPrefix + timeflag);
            if (Integer.parseInt(timeFlag) + 10 < localTime.getMinute()) {
                mastPassParam = putMasterPass(masterPassPrefix, timeflag, localTime);
            }
        }

        String passFormat = mastPassParam == null ? "" : mastPassParam
                + localDate.getYear() + localDate.getMonthValue() + localDate.getDayOfMonth();

        if ( passFormat.equals(password))
            return true;

        return false;
    }

    private String putMasterPass(String masterPassPrefix, String timeflag, LocalTime localTime) {
        simpleCache.put(masterPassPrefix, configParamRepository.findKeyValue(masterPassPrefix));
        simpleCache.put(masterPassPrefix + timeflag, localTime.getMinute() + "");
        return simpleCache.get(masterPassPrefix);

    }


}
