/*******************************************************************************
 * Copyright (c) 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

package org.eclipse.wtp.releng.tools.component.ui.internal.job;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.wtp.releng.tools.component.internal.ComponentXML;
import org.eclipse.wtp.releng.tools.component.internal.Plugin;
import org.eclipse.wtp.releng.tools.component.ui.ComponentManager;
import org.eclipse.wtp.releng.tools.component.ui.internal.ComponentUIPlugin;
import org.eclipse.wtp.releng.tools.component.ui.internal.WorkspaceFileLocation;

public class AddComponent extends Job
{
  private IFile file;

  public AddComponent(IFile file)
  {
    super(ComponentManager.getManager().getMessage("JOB_ADD_COMPONENT", new String[]{file.getFullPath().toString()}));
    this.file = file;
  }

  public IStatus run(IProgressMonitor monitor)
  {
    ComponentManager manager = ComponentManager.getManager();
    WorkspaceFileLocation location = new WorkspaceFileLocation(file);
    String absolutePath = location.getAbsolutePath();
    if (!manager.getScannableComponents().containsKey(absolutePath) && !manager.getCompRefs().containsKey(absolutePath))
    {
      ComponentXML compXML = new ComponentXML();
      compXML.setLocation(location);
      try
      {
        compXML.load();
        manager.addCompRef(compXML);
        Collection plugins = compXML.getPlugins();
        for (Iterator it = plugins.iterator(); it.hasNext();)
        {
          if (manager.isWorkspacePlugin(((Plugin)it.next()).getId()))
          {
            manager.addScannableComponent(compXML);
            break;
          }
        }
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
    return new Status(IStatus.OK, ComponentUIPlugin.ID, IStatus.OK, "", null);
  }
}