package com.homeCenter.backup;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.homeCenter.common.Log;
import com.homeCenter.common.Util;
import com.homeCenter.db.Database;

public class Task extends TimerTask {
	protected String[] files;
	protected Database db;
	
	public static final String PATH = "/opt/fhem/";
	public static final String CONFIG_FILE = "fhem.cfg";
	public static final String DATABASE_FILE = "sql.db";
	
	public Task(Database db) {
		this.files 	= new String[]{};
		this.db		= db;
	}

	public Task(Database db, String[] files) {
		this.files = files;
		this.db		= db;
	}
	
	public byte[] getZipData() throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(out);
		byte[] result = null;
		
		// Backup files
		for(int i = 0; i < this.files.length; ++i) {
			File handle = new File(this.files[i]);
			Log.info("Check file " + handle.getName() + "");
			
			if(!handle.exists()) {
				continue;
			}
			
			if(handle.isDirectory()) {
				File[] files = handle.listFiles();
				int j = 0;
				
				while(j < files.length) {
					this.zipFile(zip, files[j++]);
				}
				Log.info(i + " files added for backup in " + handle.getName());
			} else {
				this.zipFile(zip, handle);
				Log.info("Add file " + handle.getName());
			}
		}
		
		// Backup fhem config file
		if(Util.fileExists(Task.PATH + Task.CONFIG_FILE)) {
			ZipEntry entryDb = new ZipEntry(Task.CONFIG_FILE);
			zip.putNextEntry(entryDb);
			zip.write(Util.readFile(Task.PATH + Task.CONFIG_FILE));
			zip.closeEntry();
			
			Log.info("Add fhem config file");
		}
		
		// Backup database
		ZipEntry entryDb = new ZipEntry(Task.DATABASE_FILE);
		zip.putNextEntry(entryDb);
		zip.write(Util.getFileData(this.db.getDatabaseFile()));
		zip.closeEntry();
		
		zip.close();
		
		result = out.toByteArray();
		out.close();
		
		return result;
	}
	
	private void zipFile(ZipOutputStream zip, File file) throws IOException {
		ZipEntry entryDb = new ZipEntry(file.getPath());
		zip.putNextEntry(entryDb);
		zip.write(Util.readFile(file.getPath()));
		zip.closeEntry();
		
		Log.info("Add file: " + file.getPath());
	}

	@Override
	public void run() {
	}
	
	public boolean isValid() {
		return true;
	}
}
