package app.utilities.impl;


import app.utilities.FileParser;
import app.utilities.api.Serializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component(value = "JsonSerializer")
public class JsonSerializerImpl implements Serializer{

    private Gson gson;

    private FileParser parser;

    public JsonSerializerImpl() {
        gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .setPrettyPrinting()
                .create();
        this.parser = new FileParser();
    }

    @Override
    public <T> void serialize(T obj, String fileName) throws IOException {
       String json = gson.toJson(obj);
       parser.writeFile(fileName, json);
    }

    @Override
    public <T> T deserialize( Class<T> tClass, String fileName) throws IOException {
        T obj = null;
        String json = parser.readFile(fileName);
        obj = gson.fromJson(json, tClass);
        return obj;
    }
}
