# encoding: utf-8

'''
.. module:: pandasdmx.agency
    
     
    For more details on SDMX see www.sdmx.org

.. :moduleauthor :: Dr. Leo fhaxbox66@gmail.com; forked from http://github.com/widukind/pysdmx
'''



from IPython.config.configurable import LoggingConfigurable
from IPython.utils.traitlets import Instance
from pandasdmx.remote import REST
from pandasdmx.utils import str_type 
from pandasdmx.reader.sdmxml import SDMXMLReader 


__all__ = ['Request']


class Request(LoggingConfigurable):
    """
    Request SDMX data and metadata from remote or local sources.
    """
   

    client = Instance(REST, config = True, help = """
    REST or similar client to communicate with the web service""")
    
    _agencies = {
        'ESTAT' : {
            'name' : 'Eurostat',
            'url' : 'http://www.ec.europa.eu/eurostat/SDMX/diss-web/rest'},
        'ECB' : {
            'name' : 'European Central Bank',
            'url' : 'http://sdw-wsrest.ecb.int/service'}
            }
    _resources = ['dataflow', 'datastructure', 'data', 'category', 'constraint']
                    
    def __init__(self, agency = ''):
        super(Request, self).__init__()
        self.client = REST()
        if (not agency) or agency in self._agencies:
            self.agency = agency
        else:
            raise ValueError('If given, agency must be one of {0}'.format(
                            list(self._agencies)))
        

    def get_reader(self):
        return SDMXMLReader(self)
    
    
    def get(self, agency = '', resource = '', flow = '', key = '', params = {},
                 from_file = None, to_file = None):
        '''
        Load a source file identified by the URL suffix or filename given as from_file kwarg.
        If to_file is not None, save the file under that name.
        return a reader for the file as stored by self.client (mostly in a Spooled TempFile, or, if
        the downloaded file has been saved to a permanent local file, for that file.
        '''
        # Validate args
        if ((agency and agency not in self._agencies)
        or (not (agency or self.agency))):
            raise ValueError('agency must be one of {0}'.format(
                            list(self._agencies)))
        if agency: self.agency = agency
        if not (self.agency or from_file):
            raise ValueError('Either agency or from_file must be set.')    
        # 'Validate resource
        if resource and resource not in self._resources:
            raise ValueError('resource must be one of {0}'.format(self._resources))
        # flow: if it is not a str or unicode type, 
        # but, e.g., a model.DataflowDefinition, 
        # extract its ID
        if not isinstance(flow, (str_type, str)):
            flow = flow.id
            
        # Construct URL from the given non-empty substrings.
        # Remove None's and '' first. Then join them to form the base URL.
        # Any parameters are appended by remote module.
        if self.agency: 
            parts = filter(None, [self._agencies[self.agency]['url'], 
                              agency, resource, flow, key])
            base_url = '/'.join(parts)
        else: base_url = '' # in which case from_file must be True
        
        # Now get the SDMX message either via http or as local file 
        source = self.client.get(base_url, params = params, from_file = from_file)
        if to_file:
            with open(to_file, 'wb') as dest:
                dest.write(source.read())
                source.seek(0)
        return self.get_reader().initialize(source)           
@@ -724,16 +724,91 @@
 ies = %7B%0A
+        '' : None, # empty agency for convenience when from_file is given.%0A
         
@@ -1283,33 +1283,237 @@
     
-if (not agency) or agency
+self.agency = agency%0A        %0A%0A    def get_reader(self):%0A        return SDMXMLReader(self)%0A    %0A    %0A    @property%0A    def agency(self):%0A        return self._agency%0A    @agency.setter%0A    def agency(self, value):%0A        if value
  in 
@@ -1537,32 +1537,33 @@
            self.
+_
 agency = agency%0A
@@ -1547,38 +1547,37 @@
  self._agency = 
-agency
+value
 %0A        else:%0A 
@@ -1713,70 +1713,8 @@
     
-%0A%0A    def get_reader(self):%0A        return SDMXMLReader(self)%0A
     
@@ -2253,371 +2253,96 @@
     
-if ((agency and agency not in
+# Overide
  self.
-_
 agenc
-ies)%0A        or (not (agency or self.agency))):%0A            raise ValueError('agency must be one of %7B0%7D'.format(%0A                            list(self._agencies)))%0A        if agency: self.agency = agency%0A        if not (self.agency or from_file):%0A            raise ValueError('Either agency or from_file must be set.')    
+y if new agency id is gifen.%0A        if agency: self.agency = agency
 %0A   
@@ -3127,41 +3127,109 @@
   el
-se: base_url = '' # in which case
+if from_file: %0A            base_url = ''%0A        else:%0A            raise ValueError('Either agency or
  fro
@@ -3243,20 +3243,25 @@
 must be 
-True
+given.') 
 %0A       

make Request.agency a property