/*
Tiamat - a role-playing game framework
AdventureGameUtilities.java - abstract class containing utility (public static) functions used by an adventure style game
    
 Copyright  (C) 2006 Hugues Johnson
 
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

package com.huguesjohnson.tiamat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.huguesjohnson.FileCopy;
import com.huguesjohnson.PathResolver;

/** 
 * AdventureGameUtilities - abstract class containing utility (public static) functions used by an adventure style game.
 * @author Hugues Johnson
 */
public abstract class AdventureGameUtilities{

	/** 
	 * Creates a directory for a new game.
	 * @param basePath Path to source game state files.
	 * @return Path to the directory that was created.
	 */
	public final static String createGameInProgressDataDirectory(String basePath){
        String destinationPath=new String(basePath);
        if(basePath.endsWith(File.separator)){
            destinationPath=new String(basePath.substring(0,basePath.length()-File.separator.length()));
        }
        String timeStamp=String.valueOf(System.currentTimeMillis());
        destinationPath=basePath.concat(timeStamp).concat(File.separator);
        FileCopy.copyDirectory(basePath,destinationPath,true);
        return(destinationPath);
	}
	
	/** 
	 * Saves a game.
	 * @param sourcePath The path to the directory containing the game files to save.
	 * @param destinationFilePath The path to the file to create.
	 * TODO ISSUE.. WITH THIS WE CAN ONLY SAVE ONE LEVEL DEEP
	 * TODO SAVING MAY TAKE A WHILE.. CONSIDER ADDING PROGRESS
	 */
	public final static void saveGame(String sourcePath,String destinationFilePath){
        ArrayList<String> fileList=new ArrayList<String>();
        String[] list=(new File(sourcePath)).list();
        int length=list.length;
        for(int index=0;index<length;index++){
            String fullPath=sourcePath+list[index];
            File f=new File(fullPath);
            if(f.isDirectory()){
                String[] list1=f.list();
                int length1=list1.length;
                for(int index1=0;index1<length1;index1++){
                    fileList.add(fullPath+File.separator+list1[index1]);
                }
            } else{
                fileList.add(fullPath);
            }
        }
        //now write the zip
        try{
            ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(new File(destinationFilePath)));
            zout.setMethod(ZipOutputStream.DEFLATED);
            int count=fileList.size();
            for(int fileNameIndex=0;fileNameIndex<count;fileNameIndex++){
                String fileName=fileList.get(fileNameIndex);
                File file=new File(fileName);
                byte buffer[]=new byte[1024];
                int blength;
                /* generate CRC */
                CRC32 crc=new CRC32();
                FileInputStream fin=new FileInputStream(file);
                while((blength=fin.read(buffer))>-1){
                     crc.update(buffer,0,blength);
                }
                fin.close();
                /* create zip entry */
                String relativePath=PathResolver.getRelativePath(sourcePath,fileName);
                if(relativePath.startsWith("."+File.separator)){
                    relativePath=relativePath.substring(File.separator.length()+1);
                }
                ZipEntry entry=new ZipEntry(relativePath);
                entry.setSize(file.length());
                entry.setTime(file.lastModified());
                entry.setCrc(crc.getValue());
                zout.putNextEntry(entry);
                fin=new FileInputStream(file);
                /* write entry to zip file */
                while((length=fin.read(buffer))>-1){
                    zout.write(buffer,0,length);
                }
                fin.close();
                zout.closeEntry();
           }
           zout.close();
      } catch(Exception x){
           x.printStackTrace();
      }
    }
	
	/** 
	 * Unpacks a saved game to a folder.
	 * @param sourceFilePath The source file to unpack.
	 * @param destinationPath The path to the destination directory.
	 * TODO NEED SOME ERROR HANDLING IF A BAD SAVE FILE IS OPENED
	 */
	public final static void unpackSavedGame(String sourceFilePath,String destinationPath){
		try{
            ZipInputStream zin=new ZipInputStream(new FileInputStream(new File(sourceFilePath)));
            ZipEntry entry=zin.getNextEntry();
            while(entry!=null){
                byte buffer[]=new byte[1024];
                int length;
                /* write file */
                String outPath=new String(PathResolver.getAbsolutePath(destinationPath,entry.getName()));
                int lastIndexOf=outPath.lastIndexOf(File.separator);
                if(lastIndexOf>0){
                    String subDirPath=new String(outPath.substring(0,lastIndexOf));
                    File subDir=new File(subDirPath);
                    if(!subDir.exists()){
                        subDir.mkdir();
                    }
                }
                FileOutputStream fout=new FileOutputStream(new File(outPath));
                while((length=zin.read(buffer))>-1){
                    fout.write(buffer,0,length);
                }
                zin.closeEntry();
                fout.close();
                entry=zin.getNextEntry();
            }
            zin.close();
        } catch(Exception x){
            x.printStackTrace();
        }
	}	
}