package net.sourceforge.phpeclipse.mover;

/**
 * Copy the file from the source to the target directory.
 *
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import net.sourceforge.phpeclipse.views.PHPConsole;

public class CopyMover extends DefaultMover {
  /**
   * buffer, for obvious reasons access to this buffer must
   * be synchronized
   */
  protected byte[] bytes = new byte[1024];

  /**
   * Return the name the file would have after moving. In this case,
   * it's left unchanged.
   * @param file file the mover would have to move
   * @return the extension it would give the file in the target directory
   */
  public String getTargetName(File file) {
    return file.getName();
  }

  /**
   * Creates a CopyMover.
   * @param console reports error to the PHPConsole
   */
  public CopyMover(PHPConsole console) {
    super(console);
  }

  /**
   * Move one file.
   * @param sourceFile the file to move
   * @param targetDir the directory to copy the result to
   * @return file or null if the file was ignored
   */
  public File move(File sourceFile, File targetDir) {
    try {
      File targetFile = new File(targetDir, getTargetName(sourceFile));
      if (targetFile.exists())
        if (targetFile.lastModified() >= sourceFile.lastModified())
          return null;
      synchronized (bytes) {
        FileInputStream in = new FileInputStream(sourceFile);
        FileOutputStream out = new FileOutputStream(targetFile);
        for (int len = in.read(bytes); len != -1; len = in.read(bytes)) {
          out.write(bytes, 0, len);
        }
        in.close();
        out.close();
      }
      return targetFile;
    } catch (IOException e) {
      fConsole.write(e.toString());
    }
    return null;
  }
}