/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.nir.nmail.servlet;

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.stateless.NmailUserManager;
import hu.nir.nmail.ejb.stateless.UserProcesManager;
import hu.nir.nmail.threads.SenderThread;
import hu.nir.nmail.utils.NmailUtility;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.springframework.web.servlet.DispatcherServlet;

/**
 *
 * @author attila
 */
public class NmailServlet extends DispatcherServlet {

    private static Logger log = Logger.getLogger(NmailServlet.class.getName());

    @Override
    public void init(ServletConfig arg0) throws ServletException {
        super.init(arg0);
        DataManager dataManager = (DataManager) this.getWebApplicationContext().getBean("dataManager");
        try {
            log.log(Level.INFO, "Restoring started ...");
            //restore(dataManager);
            log.log(Level.INFO, "Restoring finished");
        } catch (Exception ex) {
            log.log(Level.SEVERE, "Restoring failed", ex);
        }
    }

    private void restore(DataManager dataManager) throws IOException, ClassNotFoundException {
        UserProcesManager userProcesManager = dataManager.getUserProcesManager();
        NmailUserManager nmailUserManager = dataManager.getNmailUserManager();
        List<NmailUser> nmailUserList = nmailUserManager.getAllNmailUser();

        for (NmailUser nmailUser : nmailUserList) {
            EmailSendingProces notFinishedEmailSendingProces = userProcesManager.getNotFinishedEmailSendingProceses(nmailUser);

            if (notFinishedEmailSendingProces == null) {
                continue;
            }

            byte[] emailInByteArray = notFinishedEmailSendingProces.getEmail();
            System.out.println(MimeUtility.encodeText(new String(emailInByteArray, "UTF-8"),"UTF-8",null));
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(emailInByteArray);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Message email = (Message) objectInputStream.readObject();
            List<EmailAddress> emailAddresses = nmailUserManager.getEmailAddresses(nmailUser);

            long fromIndex = notFinishedEmailSendingProces.getSentEmail();
            List<Address> addressList = new ArrayList<Address>();
            for (long i = fromIndex,  n = emailAddresses.size(); i < n; i++) {
                EmailAddress emailAddress = emailAddresses.get((int) i);
                try {
                    Address address = new InternetAddress(emailAddress.getEmailAddress());
                    addressList.add(address);
                } catch (AddressException ex) {
                    emailAddress.setWrong(true);
                    log.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
                }
            }

            nmailUser.setEmailAddressCollection(emailAddresses);
            nmailUserManager.update(nmailUser);

            //SenderThread senderThread = new SenderThread(nmailUser, email, addressList, dataManager, notFinishedEmailSendingProces);
            //senderThread.start();
        }
    }
}
