package tutorial.core.services.impl;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tutorial.core.models.entities.Account;
import tutorial.core.repositories.AccountRepo;
import tutorial.core.services.exceptions.AccountDoesNotExistException;
import tutorial.core.models.entities.Message;
import tutorial.core.repositories.MessageRepo;
import tutorial.core.services.MessageService;
import tutorial.core.services.util.MessageList;
import tutorial.rest.resources.MessageResource;

/**
 * 
 * @author Xavier
 */
@Service
@Transactional
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageRepo messageRepo;

    @Autowired
    private AccountRepo accountRepo;

    @Override
    public Message findMessage(Long id) {
        return messageRepo.findMessage(id);
    }

    @Override
    public Message createMessage(MessageResource data) {
        Account account = accountRepo.findAccountByName(data.getOwnerName());
        /*Creates the message if an account with that id exists*/
        if(account == null)
        {
            throw new AccountDoesNotExistException();
        }
        Date now = new Date();
        data.setCreated(now);
        Message message = messageRepo.createMessage(data.toMessage());
        message.setOwner(account);
        return message;
    }

    

    /*@Override
    public MessageList findMessagesByAccount(Long accountId) {
        Account account = accountRepo.findAccount(accountId);
        if(account == null)
        {
            throw new AccountDoesNotExistException();
        }
        return new MessageList(messageRepo.findMessageByAccount(accountId));
    }*/

    @Override
    public MessageList findAllMessages() {
        return new MessageList(messageRepo.findAllMessages());
    }

    @Override
    public void deleteAllMessages() {
        messageRepo.deleteAllMessages();
    }
}
