package cn.iselab.mooctest.user.service.impl;

import cn.iselab.mooctest.user.mapper.OperationRecordDao;
import cn.iselab.mooctest.user.mapper.UserMapper;
import cn.iselab.mooctest.user.model.OperationRecord;
import cn.iselab.mooctest.user.model.User;
import cn.iselab.mooctest.user.service.UserService;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author sean
 * @date 2018-03-04.
 */
@Service
@Log
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OperationRecordDao operationRecordDao;

    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    public User findByMobile(String mobile) {
        return userMapper.findByMobile(mobile);
    }

    @Override
    public User register(User user) {
        String email = user.getEmail();
        userMapper.insert(user);
        log.info(String.format("register user. name=%s, email=%s, mobile=%s, school=%s", user.getName(),
                user.getEmail(), user.getMobile(), user.getSchool()));
        user = userMapper.findByEmail(email);
        return user;
    }

    @Override
    public User findById(Long userId) {
        return userMapper.findById(userId);
    }

    @Override
    public User update(User user) {
        userMapper.updateAddress(user);
        userMapper.updateAvailability(user);
        userMapper.updateEmail(user);
        userMapper.updateMobile(user);
        userMapper.updatePassword(user);
        userMapper.updatePhotoUrl(user);
        userMapper.updateName(user);
        return userMapper.findById(user.getId());
    }

    @Override
    public OperationRecord recordOperation(OperationRecord record) {
        return operationRecordDao.save(record);
    }

    @Override
    public List<User> findByFuzzyName(String name) {
        return userMapper.findByFuzzyName(name);
    }

    @Override
    public List<User> findByFuzzyEmail(String email) {
        return userMapper.findByFuzzyEmail(email);
    }

    @Override
    public List<User> findByFuzzyNameOrEmail(String keyword) {
        return userMapper.findByFuzzyNameOrEmail(keyword);
    }

    @Override
    public List<User> findAll(List<Long> userIds) {
//        List<User> users = new ArrayList<>();
//        for (Long id : userIds) {
//            users.add(userMapper.findById(id));
//        }

        return userMapper.findAllUsers(userIds);
    }

    @Override
    public List<User> findAllByEmails(List<String> emails) {
        List<User> users = new ArrayList<>();
        for (String s : emails) {
            users.add(userMapper.findByEmail(s));
        }
        return users;
    }
}
