package com.zhongshu.card.server.core.dao.dictionary.impl;

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.dictionary.DictionaryQueryParam;
import com.zhongshu.card.client.type.DictionaryType;
import com.zhongshu.card.server.core.dao.dictionary.extend.DictionaryDaoExtend;
import com.zhongshu.card.server.core.domain.dictionary.Dictionary;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.regex.Pattern;

public class DictionaryDaoImpl implements DictionaryDaoExtend {

    @Autowired
    DBHelper dbHelper;

    @Override
    public Page<Dictionary> page(Pageable pageable, String projectId, String name, DictionaryType type) {
        Criteria criteria = new Criteria();

        if (StringUtils.isNotBlank(projectId)) {
            criteria.and("projectId").is(projectId);
        }

        if (StringUtils.isNotBlank(name)) {
            Pattern pattern = Pattern.compile("^.*" + name + ".*$");
            criteria.orOperator(Criteria.where("name").regex(pattern), Criteria.where("key").regex(pattern));
        }

        if (type != null) {
            criteria.and("type").is(type);
        }
        Query query = Query.query(criteria);

        query.with(Sort.by(Sort.Order.asc("sort"), Sort.Order.desc("createTime")));

        return dbHelper.pages(query, pageable, Dictionary.class);
    }
}
