package br.mp.mprj.portal.portlet.gestaomensagens.service.service;

import br.mp.mprj.portal.portlet.gestaomensagens.service.model.AgendamentoClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.AnexoMensagemClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.EmailDestinatarioClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.GrupoDestinatarioClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.MensagemClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.MensagemWorkflowClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.TemplateClp;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ClassLoaderObjectInputStream;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.BaseModel;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.lang.reflect.Method;

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


public class ClpSerializer {
    private static Log _log = LogFactoryUtil.getLog(ClpSerializer.class);
    private static String _servletContextName;
    private static boolean _useReflectionToTranslateThrowable = true;

    public static String getServletContextName() {
        if (Validator.isNotNull(_servletContextName)) {
            return _servletContextName;
        }

        synchronized (ClpSerializer.class) {
            if (Validator.isNotNull(_servletContextName)) {
                return _servletContextName;
            }

            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Class<?> portletPropsClass = classLoader.loadClass(
                        "com.liferay.util.portlet.PortletProps");

                Method getMethod = portletPropsClass.getMethod("get",
                        new Class<?>[] { String.class });

                String portletPropsServletContextName = (String) getMethod.invoke(null,
                        "portlet-gestao-mensagens-deployment-context");

                if (Validator.isNotNull(portletPropsServletContextName)) {
                    _servletContextName = portletPropsServletContextName;
                }
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info(
                        "Unable to locate deployment context from portlet properties");
                }
            }

            if (Validator.isNull(_servletContextName)) {
                try {
                    String propsUtilServletContextName = PropsUtil.get(
                            "portlet-gestao-mensagens-deployment-context");

                    if (Validator.isNotNull(propsUtilServletContextName)) {
                        _servletContextName = propsUtilServletContextName;
                    }
                } catch (Throwable t) {
                    if (_log.isInfoEnabled()) {
                        _log.info(
                            "Unable to locate deployment context from portal properties");
                    }
                }
            }

            if (Validator.isNull(_servletContextName)) {
                _servletContextName = "portlet-gestao-mensagens";
            }

            return _servletContextName;
        }
    }

    public static Object translateInput(BaseModel<?> oldModel) {
        Class<?> oldModelClass = oldModel.getClass();

        String oldModelClassName = oldModelClass.getName();

        if (oldModelClassName.equals(AgendamentoClp.class.getName())) {
            return translateInputAgendamento(oldModel);
        }

        if (oldModelClassName.equals(AnexoMensagemClp.class.getName())) {
            return translateInputAnexoMensagem(oldModel);
        }

        if (oldModelClassName.equals(EmailDestinatarioClp.class.getName())) {
            return translateInputEmailDestinatario(oldModel);
        }

        if (oldModelClassName.equals(GrupoDestinatarioClp.class.getName())) {
            return translateInputGrupoDestinatario(oldModel);
        }

        if (oldModelClassName.equals(MensagemClp.class.getName())) {
            return translateInputMensagem(oldModel);
        }

        if (oldModelClassName.equals(MensagemWorkflowClp.class.getName())) {
            return translateInputMensagemWorkflow(oldModel);
        }

        if (oldModelClassName.equals(TemplateClp.class.getName())) {
            return translateInputTemplate(oldModel);
        }

        return oldModel;
    }

    public static Object translateInput(List<Object> oldList) {
        List<Object> newList = new ArrayList<Object>(oldList.size());

        for (int i = 0; i < oldList.size(); i++) {
            Object curObj = oldList.get(i);

            newList.add(translateInput(curObj));
        }

        return newList;
    }

    public static Object translateInputAgendamento(BaseModel<?> oldModel) {
        AgendamentoClp oldClpModel = (AgendamentoClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getAgendamentoRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInputAnexoMensagem(BaseModel<?> oldModel) {
        AnexoMensagemClp oldClpModel = (AnexoMensagemClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getAnexoMensagemRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInputEmailDestinatario(BaseModel<?> oldModel) {
        EmailDestinatarioClp oldClpModel = (EmailDestinatarioClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getEmailDestinatarioRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInputGrupoDestinatario(BaseModel<?> oldModel) {
        GrupoDestinatarioClp oldClpModel = (GrupoDestinatarioClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getGrupoDestinatarioRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInputMensagem(BaseModel<?> oldModel) {
        MensagemClp oldClpModel = (MensagemClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getMensagemRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInputMensagemWorkflow(BaseModel<?> oldModel) {
        MensagemWorkflowClp oldClpModel = (MensagemWorkflowClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getMensagemWorkflowRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInputTemplate(BaseModel<?> oldModel) {
        TemplateClp oldClpModel = (TemplateClp) oldModel;

        BaseModel<?> newModel = oldClpModel.getTemplateRemoteModel();

        newModel.setModelAttributes(oldClpModel.getModelAttributes());

        return newModel;
    }

    public static Object translateInput(Object obj) {
        if (obj instanceof BaseModel<?>) {
            return translateInput((BaseModel<?>) obj);
        } else if (obj instanceof List<?>) {
            return translateInput((List<Object>) obj);
        } else {
            return obj;
        }
    }

    public static Object translateOutput(BaseModel<?> oldModel) {
        Class<?> oldModelClass = oldModel.getClass();

        String oldModelClassName = oldModelClass.getName();

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.AgendamentoImpl")) {
            return translateOutputAgendamento(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.AnexoMensagemImpl")) {
            return translateOutputAnexoMensagem(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.EmailDestinatarioImpl")) {
            return translateOutputEmailDestinatario(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.GrupoDestinatarioImpl")) {
            return translateOutputGrupoDestinatario(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemImpl")) {
            return translateOutputMensagem(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemWorkflowImpl")) {
            return translateOutputMensagemWorkflow(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        if (oldModelClassName.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.TemplateImpl")) {
            return translateOutputTemplate(oldModel);
        } else if (oldModelClassName.endsWith("Clp")) {
            try {
                ClassLoader classLoader = ClpSerializer.class.getClassLoader();

                Method getClpSerializerClassMethod = oldModelClass.getMethod(
                        "getClpSerializerClass");

                Class<?> oldClpSerializerClass = (Class<?>) getClpSerializerClassMethod.invoke(oldModel);

                Class<?> newClpSerializerClass = classLoader.loadClass(oldClpSerializerClass.getName());

                Method translateOutputMethod = newClpSerializerClass.getMethod("translateOutput",
                        BaseModel.class);

                Class<?> oldModelModelClass = oldModel.getModelClass();

                Method getRemoteModelMethod = oldModelClass.getMethod("get" +
                        oldModelModelClass.getSimpleName() + "RemoteModel");

                Object oldRemoteModel = getRemoteModelMethod.invoke(oldModel);

                BaseModel<?> newModel = (BaseModel<?>) translateOutputMethod.invoke(null,
                        oldRemoteModel);

                return newModel;
            } catch (Throwable t) {
                if (_log.isInfoEnabled()) {
                    _log.info("Unable to translate " + oldModelClassName, t);
                }
            }
        }

        return oldModel;
    }

    public static Object translateOutput(List<Object> oldList) {
        List<Object> newList = new ArrayList<Object>(oldList.size());

        for (int i = 0; i < oldList.size(); i++) {
            Object curObj = oldList.get(i);

            newList.add(translateOutput(curObj));
        }

        return newList;
    }

    public static Object translateOutput(Object obj) {
        if (obj instanceof BaseModel<?>) {
            return translateOutput((BaseModel<?>) obj);
        } else if (obj instanceof List<?>) {
            return translateOutput((List<Object>) obj);
        } else {
            return obj;
        }
    }

    public static Throwable translateThrowable(Throwable throwable) {
        if (_useReflectionToTranslateThrowable) {
            try {
                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(unsyncByteArrayOutputStream);

                objectOutputStream.writeObject(throwable);

                objectOutputStream.flush();
                objectOutputStream.close();

                UnsyncByteArrayInputStream unsyncByteArrayInputStream = new UnsyncByteArrayInputStream(unsyncByteArrayOutputStream.unsafeGetByteArray(),
                        0, unsyncByteArrayOutputStream.size());

                Thread currentThread = Thread.currentThread();

                ClassLoader contextClassLoader = currentThread.getContextClassLoader();

                ObjectInputStream objectInputStream = new ClassLoaderObjectInputStream(unsyncByteArrayInputStream,
                        contextClassLoader);

                throwable = (Throwable) objectInputStream.readObject();

                objectInputStream.close();

                return throwable;
            } catch (SecurityException se) {
                if (_log.isInfoEnabled()) {
                    _log.info("Do not use reflection to translate throwable");
                }

                _useReflectionToTranslateThrowable = false;
            } catch (Throwable throwable2) {
                _log.error(throwable2, throwable2);

                return throwable2;
            }
        }

        Class<?> clazz = throwable.getClass();

        String className = clazz.getName();

        if (className.equals(PortalException.class.getName())) {
            return new PortalException();
        }

        if (className.equals(SystemException.class.getName())) {
            return new SystemException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchAgendamentoException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchAgendamentoException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchAnexoMensagemException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchAnexoMensagemException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchEmailDestinatarioException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchEmailDestinatarioException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchGrupoDestinatarioException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchGrupoDestinatarioException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemWorkflowException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemWorkflowException();
        }

        if (className.equals(
                    "br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchTemplateException")) {
            return new br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchTemplateException();
        }

        return throwable;
    }

    public static Object translateOutputAgendamento(BaseModel<?> oldModel) {
        AgendamentoClp newModel = new AgendamentoClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setAgendamentoRemoteModel(oldModel);

        return newModel;
    }

    public static Object translateOutputAnexoMensagem(BaseModel<?> oldModel) {
        AnexoMensagemClp newModel = new AnexoMensagemClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setAnexoMensagemRemoteModel(oldModel);

        return newModel;
    }

    public static Object translateOutputEmailDestinatario(BaseModel<?> oldModel) {
        EmailDestinatarioClp newModel = new EmailDestinatarioClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setEmailDestinatarioRemoteModel(oldModel);

        return newModel;
    }

    public static Object translateOutputGrupoDestinatario(BaseModel<?> oldModel) {
        GrupoDestinatarioClp newModel = new GrupoDestinatarioClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setGrupoDestinatarioRemoteModel(oldModel);

        return newModel;
    }

    public static Object translateOutputMensagem(BaseModel<?> oldModel) {
        MensagemClp newModel = new MensagemClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setMensagemRemoteModel(oldModel);

        return newModel;
    }

    public static Object translateOutputMensagemWorkflow(BaseModel<?> oldModel) {
        MensagemWorkflowClp newModel = new MensagemWorkflowClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setMensagemWorkflowRemoteModel(oldModel);

        return newModel;
    }

    public static Object translateOutputTemplate(BaseModel<?> oldModel) {
        TemplateClp newModel = new TemplateClp();

        newModel.setModelAttributes(oldModel.getModelAttributes());

        newModel.setTemplateRemoteModel(oldModel);

        return newModel;
    }
}
