/*--
  This file is a part of ZetaGrid, a simple and secure Grid Computing
  kernel.

  Copyright (c) 2001-2004 Sebastian Wedeniwski.  All rights reserved.

  Use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

  1. The source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

  2. The origin of this software must not be misrepresented; you must 
     not claim that you wrote the original software.  If you plan to
     use this software in a product, please contact the author.

  3. Altered source versions must be plainly marked as such, and must
     not be misrepresented as being the original software. The author
     must be informed about these changes.

  4. The name of the author may not be used to endorse or promote 
     products derived from this software without specific prior written 
     permission.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  Version 1.9.0, February 8, 2004

  This program is based on the work of:
     S. Wedeniwski
--*/

package zeta;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class ZetaWorkUnit extends WorkUnit {

  public ZetaWorkUnit() { // ToDo: remove
    taskId = 1;
    workUnitId = -1;
    size = -1;
  }

  public ZetaWorkUnit(int taskId, long workUnitId, int size) {
    super(taskId, workUnitId, size);
  }

  public boolean isValid() {  // ToDo: remove
    return (workUnitId >= 0 && size > 0);
  }

  public boolean init(String logFilename) {
    if (isLogFilename(logFilename) && new File(logFilename).exists()) {
      try {
        int idx = logFilename.indexOf('_', 11);
        workUnitId = Long.parseLong(logFilename.substring(11, idx));
        size = Integer.parseInt(logFilename.substring(idx+1, logFilename.length()-4));
        return true;
      } catch (NumberFormatException e) {
      }
    }
    return false;
  }

  public List parseWorkUnitFiles(BufferedReader in) throws IOException {
    List workUnitFiles = new ArrayList(10);
    while (true) {
      String line = in.readLine();
      if (line == null) {
        break;
      }
      if (line.trim().length() == 0) {
        taskId = 0;
        workUnitId = -1;
        size = -1;
      } else {
        if (line.startsWith("task_id")) {
          taskId = Integer.parseInt(line.substring(line.indexOf('=') + 1).trim());
        } else if (line.startsWith("work_unit_id")) {
          workUnitId = Long.parseLong(line.substring(line.indexOf('=') + 1).trim());
        } else if (line.startsWith("size")) {
          size = Integer.parseInt(line.substring(line.indexOf('=') + 1).trim());
        } else if (line.startsWith("range")) {  // ToDo: remove
          size = Integer.parseInt(line.substring(line.indexOf('=') + 1).trim());
        }
        if (isValid()) {
          File file = new File(getLogFilename());
          file.createNewFile();
          workUnitFiles.add(getLogFilename());
        }
      }
    }
    return workUnitFiles;
  }

  public String writeObject() {
    StringBuffer buffer = new StringBuffer(8+9+13+19+6+9+7+9+2);
    buffer.append("task_id=");
    buffer.append(taskId);
    buffer.append("\nwork_unit_id=");
    buffer.append(workUnitId);
    buffer.append("\nsize=");
    buffer.append(size);
    buffer.append("\nrange=");  // ToDo: remove
    buffer.append(size);
    buffer.append("\n\n");
    return buffer.toString();
  }

  public boolean isCompleted() {
    RandomAccessFile file = null;
    try {
      file = new RandomAccessFile(getLogFilename(), "r");
      long size = file.length();
      if (size > 0) {
        file.seek(size-1);
        if (file.readByte() == (byte)'@') {
          return true;
        }
      }
    } catch (IOException ioe) {
    } finally {
      if (file != null) {
        try {
          file.close();
        } catch (IOException ioe) {
        }
      }
    }
    return false;
  }

  public String getFilename() {
    return "zeta_zeros_" + workUnitId + '_' + size + ".txt";
  }

  public String getFilename(String logFilename) {
    return (isLogFilename(logFilename))? logFilename.substring(0, logFilename.length()-3) + "txt" : null;
  }

  public String getLogFilename() {
    return "zeta_zeros_" + workUnitId + '_' + size + ".log";
  }

  public String getLogFilename(String filename) {
    return (isFilename(filename))? filename.substring(0, filename.length()-3) + "log" : null;
  }

  public boolean isFilename(String filename) {
    return filename.startsWith("zeta_zeros_") && filename.endsWith(".txt");
  }

  public boolean isLogFilename(String filename) {
    return filename.startsWith("zeta_zeros_") && filename.endsWith(".log");
  }

  public int compare(Object workUnit1, Object workUnit2) {
    if (workUnit1 == null && workUnit2 != null) return -1;
    if (workUnit1 != null && workUnit2 == null) return 1;
    if ((workUnit1 instanceof ZetaWorkUnit) && (workUnit2 instanceof ZetaWorkUnit)) {
      ZetaWorkUnit w1 = (ZetaWorkUnit)workUnit1;
      ZetaWorkUnit w2 = (ZetaWorkUnit)workUnit2;
      long wl1 = new File(w1.getLogFilename()).length();
      long wl2 = new File(w2.getLogFilename()).length();
      if (wl1 > 0 && wl2 == 0) return -1;
      if (wl1 == 0 && wl2 > 0) return 1;
      if (w1.workUnitId < w2.workUnitId) return -1;
      if (w1.workUnitId > w2.workUnitId) return 1;
      if (w1.size < w2.size) return -1;
      if (w1.size > w2.size) return 1;
    }
    return 0;
  }

  public boolean equals(Object workUnit) {  // ToDo: add taskId
    if (workUnit instanceof ZetaWorkUnit) {
      WorkUnit wu = (WorkUnit)workUnit;
      if (workUnitId == wu.workUnitId && size == wu.size) {
        return true;
      }
    }
    return false;
  }
}