const UNINSTALL_LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";

const UNINSTALL_LOCALFILEOUTPUTSTREAM_CONTRACTID =
                              "@mozilla.org/network/file-output-stream;1";

const UNINSTALL_RDONLY      = 0x01;
const UNINSTALL_WRONLY      = 0x02;
const UNINSTALL_CREATE_FILE = 0x08;
const UNINSTALL_TRUNCATE    = 0x20;
const UNINSTALL_DEFAULT_FILE_PERMS = 0600;

const UnFileChannel = new Components.Constructor( "@mozilla.org/network/local-file-channel;1", "nsIFileChannel" );

const UnInputStream = new Components.Constructor( "@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream" );

var promptSvc;

function UninstallConfirm(mesg) {
    if (!promptSvc)
	promptSvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
    return promptSvc.confirm(window, "Confirmacion", mesg);
}

function UninstallError(mesg) {
    if (!promptSvc)
	promptSvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
    return promptSvc.alert(window, "Error", mesg);
}

function UninstallAlert(mesg) {
    if (!promptSvc)
	promptSvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
    return promptSvc.alert(window, "Aviso", mesg);
}

function TesSignUninstall() {
    try {
	var delFiles = [];
	
	var confirm;
	
	confirm = UninstallConfirm("¿Realmente desea desintalar testsecclab?");
	
	if (!confirm)
	    return;
	
	// Remove installed chrome entries
	var chromeEntryRemoved = RemoveInstalledChrome("testsecclab");
	
	

	var chromeFile = GetFileOfProperty("AChrom");
	chromeFile.append("testsecclab.jar");
	
	delFiles.push(chromeFile);
	
	// Delete files
	for (var j=0; j<delFiles.length; j++) {
	    var delFile = delFiles[j];
	    if (delFile.exists()) {
		try {
		    delFile.remove(true);
		} catch (ex) {
		    UninstallError("Error borrando el fichero "+delFile.path);
		    // throw ex;
		}
	    }
	}
	
	UninstallAlert("testsecclab desinstalado con exito.");
	
    } catch (ex) {
	UninstallAlert("Problema al desinstalar: " + ex);
	
    };
}



function UninstallReadFileContents(localFile, maxBytes) {
  var fileChannel = new UnFileChannel();

  if (!localFile.exists() || !localFile.isReadable())
    throw Components.results.NS_ERROR_FAILURE;

  fileChannel.init(localFile, UNINSTALL_RDONLY, 0);

  var rawInStream = fileChannel.open();

  var scriptableInStream = new UnInputStream();    
  scriptableInStream.init(rawInStream);

  if ((maxBytes < 0) || (maxBytes > localFile.fileSize))
    maxBytes = localFile.fileSize;

  var fileContents = scriptableInStream.read(maxBytes);

  scriptableInStream.close();

  return fileContents;
}


function UninstallCreateFileStream(filePath, permissions) {

  try {
    var localFile = Components.classes[UNINSTALL_LOCAL_FILE_CONTRACTID].createInstance(Components.interfaces.nsILocalFile);

    localFile.initWithPath(filePath);

    if (localFile.exists()) {

      if (localFile.isDirectory() || !localFile.isWritable())
         throw Components.results.NS_ERROR_FAILURE;

      if (!permissions)
        permissions = localFile.permissions;
    }

    if (!permissions)
      permissions = UNINSTALL_DEFAULT_FILE_PERMS;

    var flags = UNINSTALL_WRONLY | UNINSTALL_CREATE_FILE | UNINSTALL_TRUNCATE;

    var fileStream = Components.classes[UNINSTALL_LOCALFILEOUTPUTSTREAM_CONTRACTID].createInstance(Components.interfaces.nsIFileOutputStream);

    fileStream.init(localFile, flags, permissions, 0);

    return fileStream;

  } catch (ex) {
    UninstallError("UninstallCreateFileStream: Failed to create "+filePath+"\n");
    return null;
  }
}


function UninstallWriteFileContents(filePath, data, permissions) {


  try {
    var fileOutStream = UninstallCreateFileStream(filePath, permissions);

    if (data.length) {
      if (fileOutStream.write(data, data.length) != data.length)
        throw Components.results.NS_ERROR_FAILURE;

      fileOutStream.flush();
    }
    fileOutStream.close();

  } catch (ex) {
    UninstallError("UninstallWriteFileContents: Failed to write to "+filePath+"\n");
    return false;
  }

  return true;
}


function GetFileOfProperty(prop) {
    var dscontractid = "@mozilla.org/file/directory_service;1";
    var ds = Components.classes[dscontractid].getService();
    
    var dsprops = ds.QueryInterface(Components.interfaces.nsIProperties);
    var file = dsprops.get(prop, Components.interfaces.nsIFile);
    return file;
}

function RemoveOverlay(module, urls) {

   var overlayRemoved = false;

   try {
     var overlayFile = GetFileOfProperty("AChrom");
     overlayFile.append("overlayinfo");
     overlayFile.append(module);
     overlayFile.append("content");
     overlayFile.append("overlays.rdf");


      var fileContents = UninstallReadFileContents(overlayFile, -1);

      for (var j=0; j<urls.length; j++) {
         var overlayPat=new RegExp("\\s*<RDF:li>\\s*"+urls[j]+"\\s*</RDF:li>");

         while (fileContents.search(overlayPat) != -1) {

            fileContents = fileContents.replace(overlayPat, "");

            overlayRemoved = true;

	 }
      }

      if (overlayRemoved)
         UninstallWriteFileContents(overlayFile.path, fileContents, 0);

   } catch (ex) {
       UninstallError("RemoveOverlay:" + ex);
   }

   return overlayRemoved;
}


function RemoveInstalledChrome(module) {

   var chromeEntryRemoved = false;

   try {
     var chromeListFile = GetFileOfProperty("AChrom");
     chromeListFile.append("installed-chrome.txt");

      var fileContents = UninstallReadFileContents(chromeListFile, -1);

      var chromeEntryPat = new RegExp("(content|skin|locale),install,url,jar:resource:/chrome/"+module+".*\\r?\\n?");

      while (fileContents.search(chromeEntryPat) != -1) {

         fileContents = fileContents.replace(chromeEntryPat, "");

         chromeEntryRemoved = true;
      }

      if (chromeEntryRemoved)
         UninstallWriteFileContents(chromeListFile.path, fileContents, 0);

   } catch (ex) {
       UninstallError("RemoveInstalledChrome: " + ex);
   }

   return chromeEntryRemoved;
}
