package com.avg.zaap.crashlibrary.core.writer;

import android.support.annotation.NonNull;

import com.avg.zaap.crashlibrary.core.logger.CrashLogger;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

/**
 * Implementation of {@link IDataWriter}.
 * <p>
 * Created by marek.osvald on 22. 4. 2016.
 */
public class DataWriter implements IDataWriter {

    private static final String TAG = DataWriter.class.getSimpleName();

    private IDataWriterFactory mFactory;

    /**
     * Default constructor. Uses the default dependency factory.
     */
    public DataWriter() {
        this(new DataWriterFactory());
    }

    /**
     * Parametric constructor. Sets the dependency factory to be used.
     *
     * @param factory dependency factory to be used
     */
    public DataWriter(IDataWriterFactory factory) {
        mFactory = factory;
    }

    @Override
    public void write(@NonNull String path, String data) throws DataWriterException {
        //write data to file
        if (data.trim().isEmpty()) {
            CrashLogger.e(TAG, "Data to write is empty. Wanted to write to path %s.", path);
            return;
        }

        File outputFile = mFactory.getFile(path);

        CrashLogger.d(TAG, "Path: %s", outputFile.getAbsolutePath());
        CrashLogger.d(TAG, "Data: %s", data);

        Writer writer = null;

        try {
            writer = mFactory.getBufferedWriter(mFactory.getFileWriter(outputFile));
            writer.write(data);
        } catch (IOException e) {
            CrashLogger.e(TAG, "Exception during write: %s", e.getMessage());
            throw new DataWriterException("Exception during write.", e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    CrashLogger.e(TAG, "Exception during close: %s", e.getMessage());
                }
            }
        }
    }

}
