package com.moex.asts.export;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.Map;

import com.moex.asts.export.Description.TableInfo;

public abstract class Encoder implements Closeable {

    protected final File output;

    protected PrintWriter writer;

    public Encoder(String filename) {
        output = new File(filename);
    }

    protected PrintWriter setup() throws FileNotFoundException, UnsupportedEncodingException {
        return new PrintWriter(output, "UTF-8");
    }

    public final void start() throws FileNotFoundException, UnsupportedEncodingException {
        if (writer == null)
            writer = setup();
    }

    @Override
    public void close() throws IOException {
        if (writer != null) {
            writer.close();
            writer = null;
        }
    }

    final static String DEFAULT_TYPE = ".json";

    static Encoder create(String filename) throws FileNotFoundException, UnsupportedEncodingException {
        final int index = filename.lastIndexOf('.');
        final String type;
        if (index > 0)
            type = filename.substring(index, filename.length());
        else
            type = DEFAULT_TYPE;
        switch (type.toLowerCase(Locale.US)) {
            case ".xml":
                return new XmlEncoder(filename);
            case ".json":
                return new JsonEncoder(filename);
            case ".java":
                return new JavaEncoder(filename);
            default:
                throw new IllegalArgumentException("Unknown encoder type " + type);
        }
    }

    public abstract void encode(TableInfo specs, ClientTable table, Map<String, Object> params);

}
