/*
 *  File: SwtControlPanel.java
 *  Copyright (c) 2004-2007  Peter Kliem (Peter.Kliem@jaret.de)
 *  A commercial license is available, see http://www.jaret.de.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package brn.gui.editors.timebar;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Text;

import brn.gui.editors.timebar.TimeBarEditor.IntervalFilter;

import de.jaret.util.date.JaretDate;
import de.jaret.util.ui.timebars.TimeBarViewerInterface;
import de.jaret.util.ui.timebars.ViewConfiguration;
import de.jaret.util.ui.timebars.swt.TimeBarPrinter;
import de.jaret.util.ui.timebars.swt.TimeBarViewer;

/**
 * Common settings for a timebar viewer for demonstrating.
 *
 * @author Peter Kliem
 * @version $Id: SwtControlPanel.java 300 2007-03-18 12:06:17Z olk $
 */
public class ControlPanel extends Composite {

    private TimeBarViewer _tbv;
//    private TimeBarViewer _tbv2;


    public ControlPanel(Composite arg0, int arg1, TimeBarViewer tbv) {
        super(arg0, arg1);
        _tbv = tbv;
        createControls(this);
    }

    /**
     * @param panel
     */
    private void createControls(ControlPanel panel) {
        panel.setLayout(new RowLayout());

        // this is for the millisecond example
        final Scale pixPerSecondsScale = new Scale(this, SWT.HORIZONTAL);
        pixPerSecondsScale.setMaximum(500);
        pixPerSecondsScale.setMinimum(0);
        pixPerSecondsScale.addSelectionListener(new SelectionListener() {
            public void widgetSelected(SelectionEvent ev) {
                int val = pixPerSecondsScale.getSelection();
                double pps = Math.pow(10., val/100. - 1.);
//                System.out.println("scale " + val + "pps " + pps);
                _tbv.setPixelPerSecond(pps);
            }

            public void widgetDefaultSelected(SelectionEvent arg0) {
            }
        });
        pixPerSecondsScale.setSelection((int) _tbv.getPixelPerSecond());
        RowData rd = new RowData(800, 40);
        pixPerSecondsScale.setLayoutData(rd);

        final Scale rowHeightScale = new Scale(this, SWT.HORIZONTAL);
        rowHeightScale.setMaximum(25);
        rowHeightScale.setMinimum(7);
        rowHeightScale.setSelection(_tbv.getRowHeight());
        rowHeightScale.addSelectionListener(new SelectionListener() {
            public void widgetSelected(SelectionEvent ev) {
                int val = rowHeightScale.getSelection();
                val = (int) Math.pow(10., val/10.);
                _tbv.setRowHeight(val);
            }

            public void widgetDefaultSelected(SelectionEvent arg0) {
            }
        });

        final Button gapCheck = new Button(this, SWT.CHECK);
        gapCheck.setText("GapRenderer");
        gapCheck.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent arg0) {
                if (gapCheck.getSelection()) {
                    _tbv.setGapRenderer(new IntervalGapRenderer());
                } else {
                    _tbv.setGapRenderer(null);
                }
            }
        });

        final Button drawRowGridCheck = new Button(this, SWT.CHECK);
        drawRowGridCheck.setText("Draw row grid");
        drawRowGridCheck.setSelection(_tbv.getDrawRowGrid());
        drawRowGridCheck.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent arg0) {
                _tbv.setDrawRowGrid(drawRowGridCheck.getSelection());
            }
        });

        final Button lineDragCheck = new Button(this, SWT.CHECK);
        lineDragCheck.setText("Allow line drag");
        lineDragCheck.setSelection(_tbv.isLineDraggingAllowed());
        lineDragCheck.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent arg0) {
                _tbv.setLineDraggingAllowed(lineDragCheck.getSelection());
            }
        });

        final Button optScrollingCheck = new Button(this, SWT.CHECK);
        optScrollingCheck.setText("Use optimized scrolling");
        optScrollingCheck.setSelection(_tbv.getOptimizeScrolling());
        optScrollingCheck.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent arg0) {
                _tbv.setOptimizeScrolling(optScrollingCheck.getSelection());
            }
        });

        Label l = new Label(this, SWT.NULL);
        l.setText("Orientation:");

        final CCombo orientationCombo = new CCombo(this, SWT.READ_ONLY | SWT.BORDER);
        orientationCombo.setItems(new String[] {TimeBarViewerInterface.Orientation.HORIZONTAL.toString(),
                TimeBarViewerInterface.Orientation.VERTICAL.toString()});
        int index = 0; // horizontal
        if (_tbv.getOrientation() == TimeBarViewerInterface.Orientation.VERTICAL) {
            index = 1;
        }
        orientationCombo.select(index);
        orientationCombo.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent arg0) {
                if (orientationCombo.getSelectionIndex() == 0) {
                    _tbv.setOrientation(TimeBarViewerInterface.Orientation.HORIZONTAL);
                } else if (orientationCombo.getSelectionIndex() == 1) {
                    _tbv.setOrientation(TimeBarViewerInterface.Orientation.VERTICAL);
                } else {
                    throw new RuntimeException("illegal");
                }
            }
        });

        final Label gotoLabel = new Label(this, SWT.NONE);
        gotoLabel.setText("Goto:");
        final Text gotoText = new Text(this, SWT.SINGLE | SWT.BORDER);
        gotoText.setText("         ");
        gotoText.addListener (SWT.DefaultSelection, new Listener () {
          public void handleEvent (Event e) {
            double time = Double.valueOf(gotoText.getText()).doubleValue();
            long start = (long)(time * 1000000.);
            _tbv.setStartDate(new JaretDate(start));
            IntervalFilter filter = (IntervalFilter) _tbv.getIntervalFilter();
            filter.setStart(start);
          }
        });
        gotoText.addListener(SWT.Verify, new Listener() {
          public void handleEvent(Event e) {
            String string = e.text;
            char[] chars = new char[string.length()];
            string.getChars(0, chars.length, chars, 0);
            for (int i = 0; i < chars.length; i++) {
              if (!('0' <= chars[i] && chars[i] <= '9' || chars[i] == '.')) {
                e.doit = false;
                return;
              }
            }
          }
        });
        final Label filterLabel = new Label(this, SWT.NONE);
        filterLabel.setText("Filter:");
        final Text filterText = new Text(this, SWT.SINGLE | SWT.BORDER);
        filterText.setText("         ");
        filterText.addListener (SWT.DefaultSelection, new Listener () {
          public void handleEvent (Event e) {
            IntervalFilter filter = (IntervalFilter) _tbv.getIntervalFilter();
            filter.setDetailFilter(filterText.getText());
          }
        });

        final Slider sliderStart = new Slider(this, SWT.HORIZONTAL);
        int min = (int)_tbv.getMinDate().getDate().getTime()/1000;
        int max = (int)_tbv.getMaxDate().getDate().getTime()/1000;
        sliderStart.setMinimum(min);
        sliderStart.setMaximum(max);
        sliderStart.setIncrement((max-min)/20);
        sliderStart.setPageIncrement((max-min)/5);
        sliderStart.setSelection(min);
        sliderStart.addListener (SWT.Selection, new Listener () {
          public void handleEvent (Event event) {
            IntervalFilter filter = (IntervalFilter) _tbv.getIntervalFilter();
            switch (event.detail) {
              case SWT.DRAG:
              case SWT.HOME:
              case SWT.END:
              case SWT.ARROW_DOWN:
              case SWT.ARROW_UP:
              case SWT.PAGE_DOWN:
              case SWT.PAGE_UP:
                filter.setStart(sliderStart.getSelection() * 1000L);
                break;
            }
          }
        });
        rd = new RowData(800, 40);
        sliderStart.setLayoutData(rd);
      }

    /**
     * Very simple print command.
     */
    public void print() {
        // use a stanard print dialog to choose a printer
        PrintDialog pd = new PrintDialog(Display.getCurrent().getActiveShell());
        PrinterData pdata = pd.open();
        // create the printer device
        Printer printer = new Printer(pdata);

        // create a view configuration for configuring the print
        ViewConfiguration viewConfiguration = new ViewConfiguration();
        // set the seconds per page to be the seconds displayed by the viewer
        viewConfiguration.setSecondsPerPage(_tbv.getEndDate().diffSeconds(_tbv.getStartDate()));
        // start date is the current start on the screen
        // the end date is left null -> printing will print all remaining data
        viewConfiguration.setStartDate(_tbv.getStartDate());
        // set the footer text
        viewConfiguration.setFootLine(_tbv.getTitle());
        // set a name for the viewconfiguration (this will be the name of the printing job)
        viewConfiguration.setName(_tbv.getTitle()+"_print");

        // create the time bar printer instance and initilaize it
        TimeBarPrinter tbp = new TimeBarPrinter(printer);
        tbp.init(_tbv);
        // do the actual print
        tbp.print(viewConfiguration);

        // dispose the time bar printer
        tbp.dispose();
        // dispose the printer device
        printer.dispose();
    }

}
