package com.mobvista.apptag.service.impl;

import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.entity.Tag;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.TagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.TagService;
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("tagService")
public class TagServiceImpl implements TagService {

    @Autowired
    private TagDao tagDao;

    @Autowired
    private UserDao userDao;

    @Override
    public boolean update(String packageName, String userName) {
        Tag tag = tagDao.find(packageName);
        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);
                //  this.userDao.update(user);
            }
        } else {
            tag.setTag(1);
            tag.setUserId(user.getUserId());
            user.setCount(user.getCount() + 1);
        }


        /*
        if (!user.getUserId().equals(tag.getUserId())) {
            user.setCount(user.getCount() + 1);
            this.userDao.update(user);
        }
        */

        //  tag.setUserId(user.getUserId());
        this.userDao.update(user);
        return this.tagDao.update(tag);
    }

    @Override
    public Tag find(String packageName) {
        return tagDao.find(packageName);
    }

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

        return results;
    }

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

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