/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 C.Bosquet - charles.bosquet@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package fr.gouv.finances.dgfip.xemelios.web.gwt.server.service;

import fr.gouv.finances.dgfip.xemelios.web.gwt.server.service.NoDataFoundException;
import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.user.server.rpc.UnexpectedException;
import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.services.XemeliosHelper;
import fr.gouv.finances.dgfip.xemelios.web.Application;
import fr.gouv.finances.dgfip.xemelios.web.AttributeHelper;
import fr.gouv.finances.dgfip.xemelios.web.WebAppCst;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.LabelValueDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.service.SessionExpiredException;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.utils.GWTUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * @author CBO
 */
public class AbstractXemeliosService extends RemoteServiceServlet {

    protected XemeliosUser getXemeliosUser() {
        return AttributeHelper.getUser(getThreadLocalRequest().getSession());
    }

    @Override
    protected void doUnexpectedFailure(Throwable e) {
        try {
            throw e;
        } catch (SessionExpiredException see) {
            ActionMessages actionMessages = new ActionMessages();
            actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("connexion.sessionExpiree"));
            getThreadLocalRequest().getSession().setAttribute(Globals.ERROR_KEY, actionMessages);
            writeResponseForClientRedirection(getServletContext(), getThreadLocalResponse(), getThreadLocalRequest().getContextPath());
        } catch (IncompatibleRemoteServiceException irse) {
            writeResponseForClientRedirection(getServletContext(), getThreadLocalResponse(), getThreadLocalRequest().getContextPath() + "/gwtOutOfDate.jsp");
        } catch(UnexpectedException ue) {
            try {
                throw ue.getCause();
            } catch(NoDataFoundException ndfe) {
                ActionMessages actionMessages = new ActionMessages();
                actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("search.noDataFound", XemeliosHelper.getDocumentsModel(ndfe.getDocumentId()).getTitre()));
                getThreadLocalRequest().getSession().setAttribute(Globals.ERROR_KEY, actionMessages);
                writeResponseForClientRedirection(getServletContext(), getThreadLocalResponse(), getThreadLocalRequest().getContextPath() + "/accueil.do");
            } catch(Throwable t) {
                getThreadLocalRequest().getSession().setAttribute(WebAppCst.SessionAttributes.ajaxExceptionKey, t);
                writeResponseForClientRedirection(getServletContext(), getThreadLocalResponse(), getThreadLocalRequest().getContextPath() + "/erreur.jsp");
            }
        } catch (Throwable t) {
            getThreadLocalRequest().getSession().setAttribute(WebAppCst.SessionAttributes.ajaxExceptionKey, t);
            writeResponseForClientRedirection(getServletContext(), getThreadLocalResponse(), getThreadLocalRequest().getContextPath() + "/erreur.jsp");
        }
    }

    private void writeResponseForClientRedirection(ServletContext servletContext, HttpServletResponse response, String url) {
        try {
            response.setContentType("text/plain");
            response.setStatus(GWTUtils.REMOTE_ERROR_FOR_REDIRECTION_CODE);
            response.getWriter().write(url);
        } catch (IOException ex) {
            servletContext.log("respondWithUnexpectedFailure failed while sending the previous failure to the client", ex);
        }
    }

    @Override
    protected void onBeforeRequestDeserialized(String serializedRequest) {
        if (getXemeliosUser() == null) {
            throw new SessionExpiredException();
        }
    }

    public LabelValueDTO pairToLabelValueDTO(Pair pair) {
        return new LabelValueDTO(pair.key, pair.libelle);
    }

    public List<LabelValueDTO> pairsToLabelValueDTOs(List<Pair> pairs) {
        List<LabelValueDTO> toReturn = new ArrayList<LabelValueDTO>();
        for (Pair pair : pairs) {
            toReturn.add(pairToLabelValueDTO(pair));
        }
        return toReturn;
    }
}
