/*
 * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
 *
 * http://izpack.org/
 * http://izpack.codehaus.org/
 *
 * Copyright 2004 Klaus Bartz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jp.co.ase.izpack.event;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import com.izforge.izpack.LocaleDatabase;
import com.izforge.izpack.event.NativeUninstallerListener;
import com.izforge.izpack.uninstaller.UninstallerFrame;
import com.izforge.izpack.util.AbstractUIProgressHandler;
import com.izforge.izpack.util.FileExecutor;
import com.izforge.izpack.util.Housekeeper;

/**
 * This class implements some methods which are needed by installer custom
 * actions with native parts.
 *
 * @author Klaus Bartz
 */
public class RedmineLEUninstallBatchExecuteUninstallerListener extends NativeUninstallerListener {

	/**
	 * The packs locale database.
	 */
	protected static LocaleDatabase langpack = null;

	/**
	 * Default constructor.
	 */
	public RedmineLEUninstallBatchExecuteUninstallerListener() {
		super();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.izforge.izpack.uninstaller.UninstallerListener#beforeDeletion(java
	 * .util.List, com.izforge.izpack.util.AbstractUIProgressHandler)
	 */
	public void beforeDeletion(List files, AbstractUIProgressHandler handler) throws Exception {
		try {
			// アンインストーラでインストールパスを取得するには以下のようにする
			InputStream in = UninstallerFrame.class.getResourceAsStream("/install.log");
			InputStreamReader inReader = new InputStreamReader(in);
			BufferedReader reader = new BufferedReader(inReader);
			String installPath = reader.readLine();

			String scriptPath = installPath + "/script/";
			String[] params = { scriptPath + "uninstall.bat" };

			// rubyで作成したアンインストーラを呼び出しサービスを削除(その後IzPackのアンインストーラでファイル一式を削除される）
			String[] outputParams = new String[2];
			FileExecutor fe = new FileExecutor();
			int exitStatus = fe.executeCommand(params, outputParams);
			if (exitStatus != 0) {
				// 異常系の処理 uninstall.batがない場合はメッセージを出して終了
				String title = NativeUninstallerListener.getLangpack().getString(
				        "data.validation.error.title");
				String message = NativeUninstallerListener.getLangpack().getString(
				        "uninstaller.error");
				handler.emitError(title, message);
				Housekeeper.getInstance().shutDown(0);
			}
		} catch (Exception e) {
			throw e;
		}
	}

}
