package com.mobvista.apptag.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.mobvista.apptag.entity.Tag;
import com.mobvista.apptag.entity.TagResult;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.ResultDao;
import com.mobvista.apptag.mapper.TagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.ResultService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wangjf
 */
@Service("resultService")
public class ResultServiceImpl implements ResultService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TagDao tagDao;
    @Autowired
    private ResultDao resultDao;

    @Override
    public boolean update(String packageName, String userName) {
        Tag tag = tagDao.find(packageName);
        User user = userDao.find(userName);
        if (!user.getUserId().equals(tag.getUserId())) {
            user.setCount(user.getCount() + 1);
            this.userDao.update(user);
        }
        tag.setUserId(user.getUserId());
        return this.tagDao.update(tag);
    }

    @Override
    public boolean save(String packageName, String userName, String json) {
        Tag tag = tagDao.find(packageName);
        User user = userDao.find(userName);
        TagResult tagResult = new TagResult();
        tagResult.setPackageName(packageName);
        tagResult.setAppName(tag.getAppName());
        tagResult.setPlatform(tag.getPlatform());
        tagResult.setFeatId(json);
        tagResult.setComment("comment");
        tagResult.setUserId(user.getUserId());
        tagResult.setUpdateTime(new Date());
        return this.resultDao.save(tagResult);
    }

    @Override
    public TagResult find(String packageName) {
        return resultDao.find(packageName);
    }

    @Override
    public List<TagResult> list(String userId) {
        List<TagResult> results = resultDao.list(userId);
        List<TagResult> results2 = new ArrayList<>();
        for (TagResult result : results) {
            JSONObject jsonObject = JSONObject.parseObject(result.getFeatId());
            result.setFeatId(jsonObject.values().toString());
            results2.add(result);
        }
        return results2;
    }
}