package com.mobvista.apptag.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.entity.Storage;
import com.mobvista.apptag.entity.Tag;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.StorageDao;
import com.mobvista.apptag.mapper.TagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.StorageService;
import com.mobvista.apptag.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @package: com.mobvista.apptag.service.impl
 * @author: wangjf
 * @date: 2019-08-13
 * @time: 11:05
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
@Service("storageService")
public class StorageServiceImpl implements StorageService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TagDao tagDao;
    @Autowired
    private StorageDao storageDao;

    @Override
    public boolean update(String packageName, String userName, String json) {
        Tag tag = tagDao.find(packageName);
        User user = userDao.find(userName);
        Storage storage = new Storage();
        storage.setPackageName(packageName);
        storage.setAppName(tag.getAppName());
        storage.setPlatform(tag.getPlatform());
        storage.setTag(json);
        storage.setUpdateTime(new Date());
        storage.setUserId(user.getUserId());
        return this.storageDao.save(storage);
    }

    @Override
    public Storage find(String packageName) {
        return storageDao.find(packageName);
    }

    @Override
    public List<Storage> list(Query query) {
        List<Storage> results;
        PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        results = storageDao.list(query.getSearch().toLowerCase());

        List<Storage> results2 = new ArrayList<>();
        for (Storage result : results) {
            JSONObject jsonObject = JSONObject.parseObject(result.getTag());
            result.setTag(jsonObject.values().toString());
            results2.add(result);
        }
        return results2;
    }

    @Override
    public int count(String search) {
        return storageDao.count(search);
    }
}
