package com.mobvista.apptag.service.impl;

import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.entity.ECTag;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.ECTagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.ECTagService;
import com.mobvista.apptag.utils.Query;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("ecTagService")
public class ECTagServiceImpl implements ECTagService {

    @Autowired
    private ECTagDao ecTagDao;

    @Autowired
    private UserDao userDao;

    @Override
    public boolean update(String urlMd5, String userName) {
        ECTag tag = ecTagDao.find(urlMd5);
        tag.setUpdateTime(new Date());
        User user = userDao.find(userName);
        if (StringUtils.isNotBlank(tag.getUserId())) {
            String[] userIds = tag.getUserId().split(",");
            Set set = new HashSet<>(Arrays.asList(userIds));
            if (!set.contains(user.getUserId())) {
                tag.setTag(tag.getTag() + 1);
                tag.setUserId(tag.getUserId() + "," + user.getUserId());
                user.setCount(user.getCount() + 1);
            }
        } else {
            tag.setTag(1);
            tag.setUserId(user.getUserId());
            user.setCount(user.getCount() + 1);
        }

        this.userDao.update(user);
        return this.ecTagDao.update(tag);
    }

    @Override
    public ECTag find(String urlMd5) {
        return ecTagDao.find(urlMd5);
    }

    @Override
    public List<ECTag> list(String userId, Query query) {
        User user = userDao.find(userId);
        List<ECTag> results;
        PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        results = ecTagDao.list(query.getSearch().toLowerCase(), 3, user.getUserId());

        return results;
    }

    @Override
    public int count(String userId, Query query) {
        User user = userDao.find(userId);

        return ecTagDao.count(query.getSearch().toLowerCase(), 3, user.getUserId());
    }
}