/*
 * Copyright 2007 Pentaho Corporation. All rights reserved.
 * 
 * This software was developed by Pentaho Corporation and is provided under the terms
 * of the Mozilla Public License, Version 1.1, or any later version. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
 * BI Platform. The Initial Developer is Pentaho Corporation.
 *
 * Software distributed under the Mozilla Public License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
 * the license for the specific language governing your rights and limitations.
 *
 * Created
 * @author
 * 
 */
package org.pentaho.support.standalone;

import java.io.File;
import java.util.Properties;

import org.pentaho.support.standalone.constant.SDConstant;
import org.pentaho.supportutility.util.SupportZipUtil;

public class ProgressThread implements Runnable {
	private Properties prop;
	private SDSupportUtility support;

	/**
	 * progress bar run based on set value
	 */
	@Override
	public void run() {
		int m = 2;
		for (int i = 0; i <= 200; i++) {
			if (i / m == 0) {
				m++;
				m++;
				SDSupportUtility.progressBar.setValue(i);
				SDSupportUtility.progressBar.repaint();
			}
			if (i == 200) {
				SDSupportUtility.progressBar.setVisible(false);
				SDSupportUtility.btnNewButton.setVisible(true);
				support.enableAll();
			}
			try {
				if (i == 180) {
					zipFiles();
				}
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	public void setProp(Properties prop) {
		this.prop = prop;
	}

	/**
	 * call zip
	 * 
	 * @throws InterruptedException
	 */
	private void zipFiles() throws InterruptedException {
		Thread.sleep(30000);
		SupportZipUtil.zipFile(prop);
		File file = new File(prop.getProperty(SDConstant.SUPP_INFO_DEST_PATH)
				+ File.separator + prop.getProperty(SDConstant.SUPP_INF_DIR));
		if (file.exists()) {
			delete(file);
		}
	}

	/**
	 * delete empty directory
	 * 
	 * @param file
	 */
	private void delete(File file) {
		if (file.isDirectory()) {
			if (file.list().length == 0) {
				file.delete();
			} else {
				String files[] = file.list();
				for (String temp : files) {
					File fileDelete = new File(file, temp);
					delete(fileDelete);
				}
				if (file.list().length == 0) {
					file.delete();
				}
			}
		} else {
			file.delete();
		}

	}

	public SDSupportUtility getSupport() {
		return support;
	}

	public void setSupport(SDSupportUtility support) {
		this.support = support;
	}

}
