package com.warmer.web.service.impl;

import com.hankcs.hanlp.dictionary.CustomDictionary;
import com.warmer.web.dao.CustomDictDao;
import com.warmer.web.model.CustomDictEntry;
import com.warmer.web.service.CustomDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class CustomDictServiceImpl implements CustomDictService {
    @Autowired
    private CustomDictDao customDictDao;

    private final AtomicBoolean loaded = new AtomicBoolean(false);

    @Override
    public void loadAllToHanLPIfNeeded() {
        if (loaded.compareAndSet(false, true)) {
            List<CustomDictEntry> all = customDictDao.list(null, 1);
            for (CustomDictEntry e : all) {
                try {
                    CustomDictionary.add(e.getWord(), (e.getNature() == null ? "n" : e.getNature()) + " " + (e.getFreq() == null ? 1000 : e.getFreq()));
                } catch (Exception ignored) {}
            }
        }
    }

    @Override
    public void refreshDomainToHanLP(String domain) {
        List<CustomDictEntry> items = customDictDao.list(domain, 1);
        for (CustomDictEntry e : items) {
            try {
                CustomDictionary.add(e.getWord(), (e.getNature() == null ? "n" : e.getNature()) + " " + (e.getFreq() == null ? 1000 : e.getFreq()));
            } catch (Exception ignored) {}
        }
    }

    @Override
    public List<CustomDictEntry> list(String domain, Integer enabled) {
        return customDictDao.list(domain, enabled);
    }

    @Override
    public boolean addWord(String word, String nature, Integer freq, String domain, String source) {
        if (exists(word, domain)) return true;
        CustomDictEntry e = new CustomDictEntry();
        e.setWord(word);
        e.setNature(nature == null ? "n" : nature);
        e.setFreq(freq == null ? 1000 : freq);
        e.setDomain(domain);
        e.setEnabled(true);
        e.setSource(source == null ? "manual" : source);
        int ret = customDictDao.insert(e);
        if (ret > 0) {
            try {
                CustomDictionary.add(e.getWord(), e.getNature() + " " + e.getFreq());
            } catch (Exception ignored) {}
            return true;
        }
        return false;
    }

    @Override
    public boolean disable(Integer id) {
        return customDictDao.disable(id) > 0;
    }

    @Override
    public boolean exists(String word, String domain) {
        return customDictDao.getByWord(word, domain) != null;
    }
}