/*
 * Created on Dec 11, 2004
 *
 * Part of the Symbian development plug-in for Eclipse
 * Copyright (C) Henri Muurimaa, 2004
 */
package pl.zalewski.mikolaj.symbdev.tooldetect;

import com.ice.jni.registry.NoSuchKeyException;
import com.ice.jni.registry.NoSuchValueException;
import com.ice.jni.registry.Registry;
import com.ice.jni.registry.RegistryException;
import com.ice.jni.registry.RegistryKey;

import pl.zalewski.mikolaj.symbdev.IWin32ToolConsumer;
import pl.zalewski.mikolaj.symbdev.IWin32ToolDetector;
import pl.zalewski.mikolaj.symbdev.Win32ToolEntry;

/**
 * Detects Metrowerks CodeWarrior Compiler suite. At the moment only supports
 * version 5.2.
 *
 * @author Henri Muurimaa
 */
public class MetrowerksToolDetect implements IWin32ToolDetector {

	public MetrowerksToolDetect() {
		super();
	}
	
	final String METROWERKS_CODEWARRIOR_KEY = "Software\\Metrowerks\\CodeWarrior\\!!VER!!\\Helpers";
	final String METROWERKS_CODEWARRIOR_PATH = "PATH";
	final int METROWERKS_COMPILERS_ID_MIN = Win32ToolEntry.AUTODETECTED_MIN + 0x30000;

	private Win32ToolEntry getCodeWarriorEntry(String version, int nr) {
	  	String path = null;
	  	
	  	try {
	  		RegistryKey key = Registry.HKEY_LOCAL_MACHINE.openSubKey(METROWERKS_CODEWARRIOR_KEY.replaceFirst("!!VER!!", version));
	  		path = key.getStringValue(METROWERKS_CODEWARRIOR_PATH);
	  		key.closeKey();
	  	}
	  	catch (RegistryException e) {
	  		if (!(e instanceof NoSuchKeyException) &&
	  			!(e instanceof NoSuchValueException))
	  			e.printStackTrace();
	  	    return null;
		}
	  	
	  	Win32ToolEntry result=new Win32ToolEntry();

	  	/* 
	  	 * Figure out the product name from the path. Yes, kludge...
	  	 * The path string should be of the form:
	  	 *
	  	 *	C:\\Program Files\\Metrowerks\\CodeWarrior for Symbian Pro v2.5\\bin
	  	 */
	  	try {
	  		String[] pathComponents = path.split("\\\\");
	  		result.name = pathComponents[pathComponents.length - 2];
	  	} finally {
	  		if(result.name.length() == 0)
	  			result.name = "Metrowerks CodeWarrior " + version;
	  	}
	  	
	  	result.path = path;
	  	result.target = "winscw";
	  	result.autodetected = true;
	  	result.id = METROWERKS_COMPILERS_ID_MIN + nr;

	  	return result;
	}
	
	public void detect(IWin32ToolConsumer consumer) {
	  	Win32ToolEntry ent;

	  	ent = getCodeWarriorEntry("5.2", 1); if (ent != null) consumer.entryDetected(ent);
	}
}
