/*
 * Copyright (C) 2021 - 2022 ScalAgent Distributed Technologies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s): 
 */
package fr.dyade.aaa.util.backup;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Class allowing to create a backup file.
 */
public class BackupFile extends RandomAccessFile implements Closeable {
  private int nbRecords;

  /**
   * Number of objects recorded in the file.
   * @return the number of objects recorded in the file.
   */
  public int getNbRecords() {
    return nbRecords;
  }

  /**
   * Creates a new backup file.
   * 
   * @param file  The file to create.
   * @throws IOException  An error occurs during creation.
   */
  public BackupFile(File file) throws IOException {
    super(file, "rw");
    // Writes -1 to indicate that the file is in creation
    writeInt(-1);
  }
  
  /**
   * Backups an object in the file.
   * 
   * @param buf     the byte array to store.
   * @param dirName the directory name of the object.
   * @param name    the name of the object.
   * 
   * @throws IOException An error occurs.
   */
  public synchronized void backup(BackupRecord record) throws IOException {
    nbRecords += 1;
    if (record.dirName != null) {
      writeUTF(record.dirName);
    } else {
      write(BackupRecord.emptyUTFString);
    }
    writeUTF(record.name);
    writeInt(record.value.length);
    write(record.value);
  }
  
  private volatile boolean closed;

  /**
   * Closes the backup file.
   * 
   * @throws IOException An error occurs.
   */
  public synchronized void close() throws IOException {
    if (closed) return;
    closed = true;

    // Writes the number of record at beginning of file
    seek(0L);
    writeInt(nbRecords);
    // Then close the file.
    super.close();
  }
}
