<filename>src/main/java/cz/cvut/fit/bioop/model/FileManager.java<gh_stars>0
package cz.cvut.fit.bioop.model;

import cz.cvut.fit.bioop.exceptions.CADException;
import cz.cvut.fit.bioop.exceptions.CADIllegalFileException;
import cz.cvut.fit.bioop.model.shapes.Shape;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileManager {

    private Composition mComposition;
    private OnFileSaveObserver mOnFileSaveObserver;

    public FileManager(Composition composition) {
        mComposition = composition;
    }

    public void saveToFile(File file) throws CADIllegalFileException {
        if (!cadExtension(file)) throw new CADIllegalFileException("File must have .cad extension");
        try {
            List<Shape> shapes = mComposition.allShapes();
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            StringBuilder text = new StringBuilder();
            for (Shape s : shapes) {
                text.append(s.toString());
                text.append("\n");
            }
            bufferedWriter.write(text.toString());
            bufferedWriter.close();
        } catch (IOException e) {
            throw new CADIllegalFileException(e.getMessage());
        }

        if (mOnFileSaveObserver != null)
            mOnFileSaveObserver.onFileSaved();
    }

    public void loadFromFile(File file) throws CADException {
        if (!cadExtension(file)) throw new CADIllegalFileException("File must have .cad extension");
        List<Shape> shapes = new ArrayList<>();
        try {
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String shapeString = bufferedReader.readLine();
            while (shapeString != null) {
                shapes.add(Shape.fromString(shapeString));
                shapeString = bufferedReader.readLine();
            }
            bufferedReader.close();
        } catch (IOException e) {
            throw new CADIllegalFileException(e.getMessage());
        }
        mComposition.clearShapes();
        mComposition.addAllShapes(shapes);
    }

    private boolean cadExtension(File file) {
        String filename = file.getName();
        String ext = filename.substring(filename.length() - 4);
        return ext.equals(".cad");
    }

    //==================================================================================================================
    // OBSERVER INTERFACE
    public interface OnFileSaveObserver {
        void onFileSaved();
    }
    public void setOnFileSaveObserver(OnFileSaveObserver observer) {
        mOnFileSaveObserver = observer;
    }
}
