package com.ecep.contract.ds.other.service;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.ecep.contract.ds.other.repository.SysConfRepository;
import com.ecep.contract.model.SysConf;

@Lazy
@Service
@CacheConfig(cacheNames = "sys_conf")
public class SysConfService {
    @Lazy
    @Autowired
    private SysConfRepository repository;

    public SysConf findById(String key) {
        return repository.findById(key).orElse(null);
    }

    @CacheEvict(key = "#p0.id")
    public SysConf save(SysConf conf) {
        return repository.save(conf);
    }

    @CacheEvict(key = "#p0")
    public SysConf set(String key, String value) {
        SysConf conf = findById(key);
        if (conf == null) {
            conf = new SysConf();
            conf.setId(key);
            conf.setCreated(LocalDateTime.now());
        }
        conf.setValue(value);
        conf.setModified(LocalDateTime.now());
        repository.save(conf);
        return conf;
    }

    @Cacheable(key = "#p0")
    public String getString(String key) {
        return get(key, null);
    }

    public String get(String key, String defaultValue) {
        SysConf conf = findById(key);
        if (conf == null) {
            return defaultValue;
        } else {
            return conf.getValue();
        }
    }

    @Cacheable(key = "#p0")
    public long getLong(String key) {
        return get(key, 0);
    }

    public long get(String key, long defaultValue) {
        SysConf conf = findById(key);
        if (conf == null) {
            return defaultValue;
        } else {
            return Long.parseLong(conf.getValue());
        }
    }

    @Cacheable(key = "#p0")
    public int getInt(String key) {
        return get(key, 0);
    }

    public int get(String key, int defaultValue) {
        SysConf conf = findById(key);
        if (conf == null) {
            return defaultValue;
        } else {
            return Integer.parseInt(conf.getValue());
        }
    }

    @Cacheable(key = "#p0")
    public boolean getBoolean(String key) {
        return get(key, false);
    }

    public boolean get(String key, boolean defaultValue) {
        SysConf conf = findById(key);
        if (conf == null) {
            return defaultValue;
        } else {
            if (Boolean.parseBoolean(conf.getValue())) {
                return true;
            }
            return "1".equalsIgnoreCase(conf.getValue());
        }
    }
}
