# -*- coding: utf-8 -*-
"""Provides programs to process and analyze EVE data."""
from __future__ import absolute_import

import os
import numpy as np
from datetime import datetime  

import matplotlib.pyplot as plt
from pandas.io.parsers import read_csv

from sunpy.lightcurve import LightCurve

__all__ = ['EVELightCurve']

class EVELightCurve(LightCurve):
    """SDO EVE light curve definition
    
    Examples
    --------
    import sunpy
    eve = sunpy.lightcurve.EVELightCurve.create()
    eve = sunpy.lightcurve.EVELightCurve.create('~/Downloads/EVE_Fe_IX_171_averages.csv')
    eve = sunpy.lightcurve.EVELightCurve.create('2012/06/20')
    eve = sunpy.lightcurve.EVELightCurve.create("http://lasp.colorado.edu/eve/data_access/quicklook/quicklook_data/L0CS/LATEST_EVE_L0CS_DIODES_1m.txt")
    eve.peek()
    
    References
    ----------
    | http://lasp.colorado.edu/home/eve/data/data-access/
    """

    def peek(self, column = None, **kwargs):
        figure = plt.figure()
        # Choose title if none was specified
        if not kwargs.has_key("title") and column is None:
            if len(self.data.columns) > 1:
                kwargs['title'] = 'EVE (1 minute data)'
            else:
                if self._filename is not None:
                    base = self._filename.replace('_', ' ')
                    kwargs['title'] = os.path.splitext(base)[0]
                else:
                    kwargs['title'] = 'EVE Averages'

        if column is None:
            self.plot(**kwargs)
        else:
            data = self.data[column]
            if not kwargs.has_key("title"):
                kwargs['title'] = 'EVE ' + column.replace('_', ' ')
            data.plot(**kwargs)
        figure.show()
        return figure
        
    @staticmethod
    def _get_default_uri():
        """Load latest level 0CS if no other data is specified"""
        return "http://lasp.colorado.edu/eve/data_access/quicklook/quicklook_data/L0CS/LATEST_EVE_L0CS_DIODES_1m.txt"
    
    @staticmethod
    def _get_url_for_date(date):
        """Returns a URL to the EVE data for the specified date
        
            @NOTE: currently only supports downloading level 0 data
        """
        base_url = 'http://lasp.colorado.edu/eve/data/quicklook/L0CS/SpWx/'
        return base_url + date.strftime('%Y/%Y%m%d') + '_EVE_L0CS_DIODES_1m.txt'
    
    @classmethod
    def _parse_csv(cls, filepath):
        """Parses an EVE CSV file"""
        with open(filepath, 'rb') as fp:
            # Determine type of EVE CSV file and parse
            line1 = fp.readline()
            fp.seek(0)

            if line1.startswith("Date"):
                return cls._parse_average_csv(fp)
            elif line1.startswith(";"):
                return cls._parse_level_0cs(fp)
    
    @staticmethod
    def _parse_average_csv(fp):
        """Parses an EVE Averages file"""
        return "", read_csv(fp, sep=",", index_col=0, parse_dates=True)
    
    @staticmethod
    def _parse_level_0cs(fp):
        """Parses and EVE Level 0CS file"""
        header = ""
        
        fields = ('XRS-B_proxy', 'XRS-A_proxy', 'SEM_proxy', '0.1-7ESPquad', '17.1ESP',
                  '25.7ESP', '30.4ESP', '36.6ESP', 'darkESP', '121.6MEGS-P', 'darkMEGS-P', 
                  'q0ESP', 'q1ESP', 'q2ESP', 'q3ESP', 'CMLat', 'CMLon', 'x_cool proxy', 'oldXRSB proxy')
        line = fp.readline()
        
        # Read comment at top of file
        while line.startswith(";"):
            header += line
            line = fp.readline()
            
        # Next line is YYYY DOY MM DD
        date_parts = line.split(" ")
                
        year = int(date_parts[0])
        month = int(date_parts[2])
        day = int(date_parts[3])
        
        # function to parse date column (HHMM)
        parser = lambda x: datetime(year, month, day, int(x[0:2]), int(x[2:4]))

        data = read_csv(fp, sep="\s*", names=fields, index_col=0, date_parser=parser, comment = ';', header = None)
        data.columns = fields
        return header, data

@@ -491,98 +491,8 @@
 e()%0A
-    eve = sunpy.lightcurve.EVELightCurve.create('~/Downloads/EVE_Fe_IX_171_averages.csv')%0A
     
@@ -2095,16 +2095,74 @@
  0 data%0A
+            .TODO: No data available prior to 2010/03/01!%0A
         
@@ -3032,27 +3032,18 @@
 eader = 
-%22%22%0A        
+%5B%5D
 %0A       
@@ -3056,275 +3056,10 @@
 s = 
-('XRS-B_proxy', 'XRS-A_proxy', 'SEM_proxy', '0.1-7ESPquad', '17.1ESP',%0A                  '25.7ESP', '30.4ESP', '36.6ESP', 'darkESP', '121.6MEGS-P', 'darkMEGS-P', %0A                  'q0ESP', 'q1ESP', 'q2ESP', 'q3ESP', 'CMLat', 'CMLon', 'x_cool proxy', 'oldXRSB proxy')
+%5B%5D
 %0A   
@@ -3084,32 +3084,51 @@
 dline()%0A        
+header.append(line)
 %0A        # Read 
@@ -3127,23 +3127,22 @@
  # Read 
-comment
+header
  at top 
@@ -3207,16 +3207,21 @@
 ader
- += 
+.append(
 line
+)
 %0A   
@@ -3246,32 +3246,33 @@
 .readline()%0A
+%0A
         
     %0A       
@@ -3251,36 +3251,374 @@
 line()%0A%0A        
-    
+fieldnames_start = False%0A        for l in header:%0A            if l.startswith(%22; Format:%22):%0A                fieldnames_start = False%0A            if fieldnames_start:%0A                fields.append(l.split(%22:%22)%5B0%5D.replace(';', ' ').strip())        %0A            if l.startswith(%22; Column descriptions:%22):%0A                fieldnames_start = True%0A
 %0A        # Next 
@@ -3639,16 +3639,24 @@
 OY MM DD
+        
 %0A       
@@ -3804,16 +3804,116 @@
 rts%5B3%5D)%0A
+        #last_pos = fp.tell()%0A        #line = fp.readline()%0A        #el = line.split()%0A        #len%0A
         
@@ -4130,23 +4130,8 @@
 ser,
- comment = ';',
  hea
@@ -4146,24 +4146,25 @@
 ne)%0A        
+#
 data.columns

fix for issue #423