/*
 * Copyright (C) 2014  Ohm Data
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package c5db.replication;

import c5db.ConfigDirectory;

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

import static c5db.C5ServerConstants.REPLICATOR_PERSISTER_FILE_NAME;

/**
 * A small persister that writes files to a directory. Persisting this information is needed to
 * provide crash recovery for {@link c5db.replication.ReplicatorInstance}.
 */
class Persister implements ReplicatorInfoPersistence {

  private final ConfigDirectory configDirectory;

  Persister(ConfigDirectory configDirectory) {
    this.configDirectory = configDirectory;
  }

  @Override
  public long readCurrentTerm(String quorumId) throws IOException {
    return getLongofFile(quorumId, 0);
  }

  @Override
  public long readVotedFor(String quorumId) throws IOException {
    return getLongofFile(quorumId, 1);
  }

  private long getLongofFile(String quorumId, int whichLine) throws IOException {
    List<String> datas = configDirectory.readFile(configDirectory.getQuorumRelPath(quorumId),
        REPLICATOR_PERSISTER_FILE_NAME);
    if (datas.size() != 2) {
      return 0; // corrupt file?
    }

    try {
      return Long.parseLong(datas.get(whichLine));
    } catch (NumberFormatException e) {
      return 0; // corrupt file sucks?
    }
  }

  @Override
  public void writeCurrentTermAndVotedFor(String quorumId, long currentTerm, long votedFor) throws IOException {
    List<String> datas = new ArrayList<>(2);
    datas.add(Long.toString(currentTerm));
    datas.add(Long.toString(votedFor));
    configDirectory.writeFile(configDirectory.getQuorumRelPath(quorumId), REPLICATOR_PERSISTER_FILE_NAME, datas);
  }
}

@@ -1391,33 +1391,33 @@
   return getLong
-o
+O
 fFile(quorumId, 
@@ -1516,25 +1516,25 @@
 turn getLong
-o
+O
 fFile(quorum
@@ -1568,17 +1568,17 @@
  getLong
-o
+O
 fFile(St
@@ -1649,17 +1649,16 @@
 ng%3E data
-s
  = confi
@@ -1774,17 +1774,16 @@
 if (data
-s
 .size() 
@@ -1872,17 +1872,16 @@
 ong(data
-s
 .get(whi
@@ -2126,17 +2126,16 @@
 ng%3E data
-s
  = new A
@@ -2149,33 +2149,32 @@
 t%3C%3E(2);%0A    data
-s
 .add(Long.toStri
@@ -2199,17 +2199,16 @@
     data
-s
 .add(Lon
@@ -2340,17 +2340,16 @@
 ME, data
-s
 );%0A  %7D%0A%7D

Fix Persister spelling nits