package org.csstudio.trends.databrowser.plotpart;

import org.csstudio.archive.ArchiveServer;
import org.csstudio.archive.cache.ArchiveCache;
import org.csstudio.archive.crawl.BatchIterator;
import org.csstudio.platform.data.ITimestamp;
import org.csstudio.platform.data.IValue;
import org.csstudio.platform.model.IArchiveDataSource;
import org.csstudio.trends.databrowser.Plugin;
import org.csstudio.trends.databrowser.model.IPVModelItem;
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;

/** Eclipse background job for fetching samples from the data server.
 *  @author Kay Kasemir
 */
class ArchiveFetchJob extends Job
{
    private IPVModelItem item;
    private ITimestamp start, end;
    
    /** Create job that searches given server's keys for pattern,
     *  then notifies view about received names.
     */
    public ArchiveFetchJob(IPVModelItem item, ITimestamp start, ITimestamp end)
    {
        super(Messages.FetchDataForPV
                + "'" + item.getName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
        this.item = item;
        this.start = start;
        this.end = end;
        // Do we need to assert that only one data fetch runs at a time?
        // setRule()...?
    }
    
    @SuppressWarnings("nls")
    @Override
    protected IStatus run(final IProgressMonitor monitor)
    {
        final IArchiveDataSource archives[] = item.getArchiveDataSources();
        monitor.beginTask(Messages.FetchingSample, archives.length);
        for (int i=0; i<archives.length; ++i)
        {
            // Display "N/total", using '1' for the first sub-archive.
            monitor.subTask(Messages.Fetch_Archive
                + "'" + archives[i].getName()
                + "' ("
                + (i+1) + "/" + archives.length + ")");
            final ArchiveCache cache = ArchiveCache.getInstance();
            try
            {   // Invoke the possibly lengthy search.
                final ArchiveServer server =
                    cache.getServer(archives[i].getUrl());
                
                // TODO: Get something better than PLOTBINNED
                final String request_type = 
                    item.getRequestType() == IPVModelItem.RequestType.RAW
                    ? ArchiveServer.GET_RAW
                    : ArchiveServer.GET_PLOTBINNED;
                int bins = 800;
                final Object[] request_parms = new Object[] { new Integer(bins) };
                
                BatchIterator batch = new BatchIterator(server,
                                archives[i].getKey(), item.getName(),
                                start, end, request_type, request_parms);
                IValue result[] = batch.getBatch();
                while (result != null)
                {   // Notify model of new samples.
                    // Even when monitor.isCanceled at this point?
                    // Yes, since we have the samples, might as well show them
                    // before bailing out.
                    if (result.length > 0)
                        item.addArchiveSamples(server.getServerName(), result);
                    if (monitor.isCanceled())
                        break;
                    result = batch.next();
                }
            }
            catch (Exception ex)
            {
                Plugin.logException("ArchiveFetchJob", ex);
            }
            // Stop and ignore further results when canceled.
            if (monitor.isCanceled())
                return Status.CANCEL_STATUS;
            // Handled one sub-archive.
            monitor.worked(1);
        }
        monitor.done();
        return Status.OK_STATUS;
    }
}
@@ -2214,22 +2214,16 @@
         
-final 
 String r
@@ -2237,32 +2237,108 @@
 type
- = %0A                    
+;%0A                Object%5B%5D request_parms;%0A                final int bins = 800;%0A                if (
 item
@@ -2386,16 +2386,35 @@
 Type.RAW
+)%0A                %7B
 %0A       
@@ -2426,17 +2426,30 @@
         
-?
+request_type =
  Archive
@@ -2462,16 +2462,17 @@
 .GET_RAW
+;
 %0A       
@@ -2484,17 +2484,159 @@
         
-:
+request_parms = new Object%5B%5D %7B new Integer(bins) %7D;%0A                %7D%0A                else%0A                %7B%0A                    request_type =
  Archive
@@ -2646,26 +2646,23 @@
 ver.GET_
-PLOTBINNED
+AVERAGE
 ;%0A      
@@ -2675,106 +2675,196 @@
     
-int bins = 800;%0A                final Object%5B%5D request_parms = new Object%5B%5D %7B new Integer(bins) %7D;
+    final double interval =%0A                        (end.toDouble() - start.toDouble()) / bins;%0A                    request_parms = new Object%5B%5D %7B new Double(interval) %7D;%0A                %7D
 %0A   

Ask for 'average' with delta.