/*******************************************************************************
 * Copyright (c) 2006 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.adopter.preference;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.wtp.releng.tools.component.adopters.References;
import org.eclipse.wtp.releng.tools.component.ui.Message;
import org.eclipse.wtp.releng.tools.component.ui.internal.ComponentUIPlugin;

public class UsageReportsPrefPage extends PreferencePage implements IWorkbenchPreferencePage, SelectionListener
{
  private List reports;
  private Button add;
  private Button remove;
  private Text output;
  private Button browse;

  protected Control createContents(Composite superparent)
  {
    Composite parent = new Composite(superparent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    parent.setLayout(layout);
    parent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Label label = new Label(parent, SWT.READ_ONLY | SWT.WRAP);
    label.setText(Message.getMessage("LABEL_ADOPTER_USAGE_REPORTS"));
    label.setLayoutData(new GridData( GridData.FILL_HORIZONTAL));

    Composite c = new Composite(parent, SWT.NONE);
    GridLayout gl = new GridLayout();
    gl.numColumns = 2;
    gl.marginHeight = 0;
    gl.marginWidth = 0;
    c.setLayout(gl);
    c.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ));

    reports = new List(c, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
    GridData gd = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
    gd.widthHint = 256;
    reports.setLayoutData(gd);

    Composite c2 = new Composite(c, SWT.NONE);
    gl = new GridLayout();
    gl.numColumns = 1;
    gl.marginHeight = 10;
    gl.marginWidth = 0;
    c2.setLayout(gl);

    add = new Button(c2, SWT.PUSH);
    add.setText(Message.getMessage("LABEL_ADD"));
    add.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    add.addSelectionListener(this);

    remove = new Button(c2, SWT.PUSH);
    remove.setText(Message.getMessage("LABEL_REMOVE"));
    remove.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    remove.addSelectionListener(this);
    
    label = new Label(c, SWT.READ_ONLY | SWT.WRAP);
    label.setText("");
    gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
    gd.horizontalSpan = 2;
    label.setLayoutData(gd);

    label = new Label(c, SWT.READ_ONLY | SWT.WRAP);
    label.setText(Message.getMessage("LABEL_BREAKAGE_REPORT_OUTPUT_DIR"));
    label.setLayoutData(gd);

    output = new Text(c, SWT.READ_ONLY | SWT.WRAP | SWT.BORDER);
    output.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    browse = new Button(c, SWT.PUSH);
    browse.setText(Message.getMessage("LABEL_BROWSE"));
    browse.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    browse.addSelectionListener(this);

    initValues();
    return parent;
  }

  protected void performDefaults()
  {
    super.performDefaults();
  }

  /**
   * Do anything necessary because the OK button has been pressed.
   *  @return whether it is okay to close the preference page
   */
  public boolean performOk()
  {
    storeValues();
    return true;
  }

  protected void performApply()
  {
    performOk();
  }

  private void initValues()
  {
    IPreferenceStore pref = ComponentUIPlugin.getDefault().getPreferenceStore();
    String value = pref.getString("UsageReportPrefPage");
    StringTokenizer st = new StringTokenizer(value, "#");
    java.util.List containers = new ArrayList();
    while (st.hasMoreTokens())
    {
      String token = st.nextToken();
      reports.add(token);
      containers.add(token);
    }
    reloadRefs(containers);
    
    // output
    String outputValue = pref.getString("UsageReportPrefPage.output");
    output.setText(outputValue);
  }

  private void storeValues()
  {
    StringBuffer sb = new StringBuffer();
    java.util.List containers = new ArrayList();
    String[] s = reports.getItems();
    for (int i = 0; i < s.length; i++)
    {
      sb.append(s[i]);
      sb.append("#");
      containers.add(s[i]);
    }
    if (sb.length() > 0)
      sb.deleteCharAt(sb.length() - 1);
    IPreferenceStore pref = ComponentUIPlugin.getDefault().getPreferenceStore();
    pref.setValue("UsageReportPrefPage", sb.toString());
    reloadRefs(containers);
    
    // output
    pref.setValue("UsageReportPrefPage.output", output.getText());
  }

  public void init(IWorkbench desktop)
  {
  }

  public void widgetDefaultSelected(SelectionEvent e)
  {
  }

  public void widgetSelected(SelectionEvent e)
  {
    if (e.widget == add)
    {
      String[] excludes = reports.getItems();
      java.util.List list = new ArrayList(excludes.length);
      for (int i = 0; i < excludes.length; i++)
      {
        list.add(excludes[i]);
      }
      ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), true, list);
      if (dialog.open() == Dialog.OK)
      {
        IContainer[] containers = dialog.getSelections();
        if (containers != null)
        {
          for (int i = 0; i < containers.length; i++)
          {
            reports.add(containers[i].getFullPath().toString());
          }
        }
      }
    }
    else if (e.widget == remove)
    {
      reports.remove(reports.getSelectionIndices());
    }
    else if (e.widget == browse)
    {
      ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), false, null);
      if (dialog.open() == Dialog.OK)
      {
        IContainer[] container = dialog.getSelections();
        if (container != null && container.length > 0)
        {
          output.setText(container[0].getFullPath().toString());
        }
      }
    }
  }

  private static java.util.List refs = null;

  public static java.util.List getReferences()
  {
    if (refs == null)
    {
      IPreferenceStore pref = ComponentUIPlugin.getDefault().getPreferenceStore();
      String value = pref.getString("UsageReportPrefPage");
      StringTokenizer st = new StringTokenizer(value, "#");
      java.util.List containers = new ArrayList();
      while (st.hasMoreTokens())
      {
        containers.add(st.nextToken());
      }
      reloadRefs(containers);
    }
    return refs;
  }

  public static IContainer getOutput()
  {
    IPreferenceStore pref = ComponentUIPlugin.getDefault().getPreferenceStore();
    String outputValue = pref.getString("UsageReportPrefPage.output");
    if (outputValue != null)
    {
      return (IContainer)ResourcesPlugin.getWorkspace().getRoot().findMember(outputValue);
    }
    else
    {
      return null;
    }
  }

  private static void reloadRefs(java.util.List containers)
  {
    refs = new ArrayList();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    for (Iterator it = containers.iterator(); it.hasNext();)
    {
      IContainer container = (IContainer)root.findMember((String)it.next());
      if (container != null)
      {
        try
        {
          container.accept(new IResourceProxyVisitor()
          {
            public boolean visit(IResourceProxy proxy) throws CoreException
            {
              if (proxy.getName().endsWith(".xml"))
              {
                References ref = new References();
                try
                {
                  ref.load(((IFile)proxy.requestResource()).getContents());
                  refs.add(ref);
                }
                catch (Throwable t)
                {
                  t.printStackTrace();
                }
              }
              return true;
            }
          }, IContainer.NONE);
        }
        catch (CoreException ce)
        {
          ce.printStackTrace();
        }
      }
    }
  }
}