/*-
 * ~~~~~~licensing~~~~~~
 * cluster-persistence-service
 * ==========
 * 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.platform.core.cluster.persistence;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Serializer<T> {

	private static final Logger log = LoggerFactory.getLogger(Serializer.class);
	
	
	private Class<T> dataClass;
	
	public Serializer(Class<T> clazz) {
		this.dataClass = clazz;
	} 
	
	public String toString(T object) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
		try {
			oos = new ObjectOutputStream( baos );
	        oos.writeObject((Serializable) object);
	        oos.close();
		} catch (IOException e) {
			log.error("Serializer.toString", e);
		}
        return Base64.getEncoder().encodeToString(baos.toByteArray());			
	}
	
	public T fromString(String str) {
        byte [] data = Base64.getDecoder().decode(str);
        // ClassLoader original = Thread.currentThread().getContextClassLoader();
        // Thread.currentThread().setContextClassLoader(dataClass.getClassLoader());
        T result = null;
        try {
	        ObjectInputStream ois = new ObjectInputStream( 
	                                        new ByteArrayInputStream(  data ) );
	        Object o  = ois.readObject();
	        ois.close();
	        result = dataClass.cast(o);
        } catch (Exception e) {
        	result = null;
        }
        // Thread.currentThread().setContextClassLoader(original);
        return result;
	}
	
}
