"""
Class for reading data from Elan.

Elan is software for studying time-frequency maps of EEG data.

Elan is developed in Lyon, France, at INSERM U821

https://elan.lyon.inserm.fr

An Elan dataset is separated into 3 files :
 - .eeg          raw data file
 - .eeg.ent      hearder file
 - .eeg.pos      event file

Author: Samuel Garcia

"""

from .baserawio import (BaseRawIO, _signal_channel_dtype, _unit_channel_dtype,
                        _event_channel_dtype)

import numpy as np

import datetime
import os
import re
import io


class ElanRawIO(BaseRawIO):
    extensions = ['eeg']
    rawmode = 'one-file'

    def __init__(self, filename=''):
        BaseRawIO.__init__(self)
        self.filename = filename

    def _parse_header(self):

        with open(self.filename + '.ent', mode='rt', encoding='ascii', newline=None) as f:

            # version
            version = f.readline()[:-1]
            assert version in ['V2', 'V3'], 'Read only V2 or V3 .eeg.ent files. %s given' % version

            # info
            info1 = f.readline()[:-1]
            info2 = f.readline()[:-1]

            # strange 2 line for datetime
            # line1
            l = f.readline()
            r1 = re.findall(r'(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)', l)
            r2 = re.findall(r'(\d+):(\d+):(\d+)', l)
            r3 = re.findall(r'(\d+)-(\d+)-(\d+)', l)
            YY, MM, DD, hh, mm, ss = (None,) * 6
            if len(r1) != 0:
                DD, MM, YY, hh, mm, ss = r1[0]
            elif len(r2) != 0:
                hh, mm, ss = r2[0]
            elif len(r3) != 0:
                DD, MM, YY = r3[0]

            # line2
            l = f.readline()
            r1 = re.findall(r'(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)', l)
            r2 = re.findall(r'(\d+):(\d+):(\d+)', l)
            r3 = re.findall(r'(\d+)-(\d+)-(\d+)', l)
            if len(r1) != 0:
                DD, MM, YY, hh, mm, ss = r1[0]
            elif len(r2) != 0:
                hh, mm, ss = r2[0]
            elif len(r3) != 0:
                DD, MM, YY = r3[0]
            try:
                fulldatetime = datetime.datetime(int(YY), int(MM), int(DD),
                                                 int(hh), int(mm), int(ss))
            except:
                fulldatetime = None

            l = f.readline()
            l = f.readline()
            l = f.readline()

            # sampling rate sample
            l = f.readline()
            self._sampling_rate = 1. / float(l)

            # nb channel
            l = f.readline()