/*-
 * ~~~~~~licensing~~~~~~
 * events-handler
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.core.events.handler.util;

import com.google.gson.ExclusionStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.camel.component.gson.GsonDataFormat;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class GsonDataFormatInitializer extends GsonDataFormat {

    private Gson gson;

    public GsonDataFormatInitializer() {
        super();
        Type type = new TypeToken<ArrayList<SystemSubscription>>() {
        }.getType();
        setUnmarshalGenericType(type);
    }

    @Override
    protected void doStart() throws Exception {
        if (gson == null) {
            GsonBuilder builder = new GsonBuilder();
            if (getExclusionStrategies() != null && !getExclusionStrategies().isEmpty()) {
                ExclusionStrategy[] strategies = getExclusionStrategies().toArray(new ExclusionStrategy[getExclusionStrategies().size()]);
                builder.setExclusionStrategies(strategies);
            }
//            if (longSerializationPolicy != null) {
//                builder.setLongSerializationPolicy(longSerializationPolicy);
//            }
            if (getFieldNamingPolicy() != null) {
                builder.setFieldNamingPolicy(getFieldNamingPolicy());
            }
//            if (fieldNamingStrategy != null) {
//                builder.setFieldNamingStrategy(fieldNamingStrategy);
//            }
//            if (serializeNulls) {
//                builder.serializeNulls();
//            }
//            if (prettyPrint) {
//                builder.setPrettyPrinting();
//            }
//            if (dateFormatPattern != null) {
//                builder.setDateFormat(dateFormatPattern);
//            }

            builder.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);

            gson = builder.create();

            Field f1 = this.getClass().getSuperclass().getDeclaredField("gson");
            f1.setAccessible(true);
            f1.set(this, gson);
        }
    }

}
