package org.academiadecodigo.enuminatti.paint.file;

import java.io.*;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

// TODO: Add header to know original cols/rows
// TODO: Gracefully handle differently sized saves somehow
// TODO: Use higher base to handle more colors/sprites

public class Save {
    public static char[] load(int cols, int rows, String savefile) {
        char[] cellsToLoad;

        try (FileReader fileReader = new FileReader(savefile);
                BufferedReader reader = new BufferedReader(fileReader)) {

            String cellLine = reader.readLine();

            if (cellLine == null || cellLine.length() != cols*rows) {
                throw new IllegalArgumentException();
            }

            cellsToLoad = cellLine.toCharArray();

        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
            cellsToLoad = loadEmptyGrid(cols, rows);
        }

        return cellsToLoad;
    }

    public static void save(char[] cells, String savefile) {
        try (FileWriter fileWriter = new FileWriter(savefile);
                BufferedWriter writer = new BufferedWriter(fileWriter)) {

            writer.write(new String(cells), 0, cells.length);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static char[] loadEmptyGrid(int cols, int rows) {
        char[] cells = new char[cols * rows];
        for (int i = 0; i < cells.length; i++) {
            cells[i] = '0';
        }
        return cells;
    }
}
