#! /usr/bin/env python
import quantities as pq
import gdfio
import neo
import os
from active_worker.task import task
from task_types import TaskTypes as tt


@task
def gdf2NeoH5_task(gdf_file, t_start, t_stop, gdf_id_list):
    """
        Task Manifest Version: 1
        Full Name: gdf2NeoH5_task
        Caption: Convert GDF to NeoHDF5
        Author: NEST and Elephant Developers
        Description: |
            Takes a GDF file containing spike data generated by
            NEST (http://nest-simulator.org/) and converts it to a
            NeoHDF5 file which can be processed by Elephant
            (http://neuralensemble.org/elephant).
        Categories:
            - NEST
            - FDAT
        Compatible_queues: ['cscs_viz', 'cscs_bgq', 'epfl_viz']
        Accepts:
            gdf_file:
                type: application/vnd.juelich.nest.spike_times
                description: Input file that contains spike data from a
                    NEST simulation in GDF format.
            t_start:
                type: double
                description: Start time in ms of spike train recording.
            t_stop:
                type: double
                description: Stop time in ms of spike train recording.
            gdf_id_list:
                type: list(long)
                description: Neuron IDs in the input file that should be
                    extracted, e.g., [1, 2, 3]. Provide an empty list [] to
                    extract all neurons with at least one spike.
        Returns:
            res: application/unknown
    """

    gdf = gdf2NeoH5_task.task.uri.get_file(gdf_file)
    input_file = gdfio.GdfIO(gdf)
    seg = input_file.read_segment(gdf_id_list=gdf_id_list,
                                  t_start=t_start * pq.ms,
                                  t_stop=t_stop * pq.ms)
    output_filename = os.path.splitext(gdf)[0] + '.h5'
    output_file = neo.io.NeoHdf5IO(output_filename)
    output_file.write(seg.spiketrains)
    output_file.close()

    output_dst = output_filename.split('/')[-1]

    return gdf2NeoH5_task.task.uri.save_file(
        mime_type='application/unknown',
        src_path=output_filename,
        dst_path=output_dst)


if __name__ == '__main__':
    input_filename = tt.URI('application/unknown',
                            'spikes_L4E-77177-0.gdf')
    t_start = 0.
    t_stop = 300.
    gdf_id_list = []
    gdf2NeoH5_task(input_filename, t_start, t_stop, gdf_id_list)
