/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.nir.nmail.services;

import hu.nir.nmail.dbm.DataManager;
import hu.nir.nmail.ejb.entity.EmailAddress;
import hu.nir.nmail.ejb.entity.EmailSendingProces;
import hu.nir.nmail.ejb.entity.NmailUser;
import hu.nir.nmail.ejb.entity.UserSetting;
import hu.nir.nmail.ejb.stateless.NmailUserManager;
import hu.nir.nmail.ejb.stateless.UserProcesManager;
import hu.nir.nmail.spring.beans.DatabaseInformation;
import hu.nir.nmail.spring.beans.TimeRestrictionInformation;
import hu.nir.nmail.utils.NmailUtility;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @author attila
 */
public class InfoService implements NmailService {
    private DataManager dataManager;
    
    public Map<String, Object> processCommand(Object... commands) {
        NmailUser nmailUser = null;
        for(Object command : commands) {
            if (command instanceof NmailUser) {
                nmailUser = (NmailUser) command;
                continue;
            }
        }
        
        if (nmailUser == null) {
            return null;
        }

        NmailUserManager nmailUserManager = dataManager.getNmailUserManager();
        List<EmailAddress> emailAddressList = nmailUserManager.getEmailAddresses(nmailUser);
        DatabaseInformation databaseInformation = new DatabaseInformation("NMAIL", emailAddressList.size(), 0, 0);
        List<DatabaseInformation> databaseInformationList = new ArrayList<DatabaseInformation>();
        databaseInformationList.add(databaseInformation);

        UserProcesManager userProcesManager = dataManager.getUserProcesManager();
        EmailSendingProces lastEmailSendingProces = userProcesManager.getLastEmailSendingProces(nmailUser);
        UserSetting userSetting = nmailUser.getUserSetting();
        
        Date lastSendDate = null;
        Date nextPossibleSendDate = null;
        
        if (lastEmailSendingProces != null) {
            lastSendDate = lastEmailSendingProces.getStartProces();
            long timeLimit = userSetting.getTimeLimit().longValue();
            nextPossibleSendDate = new Date(lastSendDate.getTime()+timeLimit);
        }
        
        TimeRestrictionInformation timeRestrictionInformation = new TimeRestrictionInformation(lastSendDate, nextPossibleSendDate);
        
        
        return NmailUtility.toMap("databaseInformationList", databaseInformationList, "timeRestriction", timeRestrictionInformation);
    }

    public DataManager getDataManager() {
        return dataManager;
    }

    public void setDataManager(DataManager dataManager) {
        this.dataManager = dataManager;
    }

}
