#!/usr/bin/env python

from ckanclient.loaders.base import SimpleGoogleSpreadsheetLoader 

class NorwegianGovernmentLoader(SimpleGoogleSpreadsheetLoader):
    """
    Obtains packages from Norwegian Government spreadsheet and puts them on CKAN.
    """
    
    HEADING_ROW_POSN = 1
    FIRST_ENTITY_ROW_POSN = 3

    def entity_to_package(self, entity):
        """Makes a CKAN package from Norwegian Government spreadsheet entity."""
        if entity.get('Unik identifikator', ''):
            updated_by = entity.pop('Oppdatert av', '')
            source_of_data = entity.pop('URL til kilde for data', '')
            more_information = entity.pop('URL til kilde for data', '')
            accessible = entity.get('Tilgjengelig?', '')
            license_id = ''
            license_title = ''
            if accessible and accessible[0] == 'J':
                license_id = 'other-open'
                license_title = 'OKD Compliant::Other' # Pre-licenses servization.
            elif accessible and accessible[0] == 'N':  
                license_id = 'other-closed' 
                license_title = 'Non-OKD Compliant::Other' # Pre-licenses servization.
            resources = []
            if source_of_data:
                resources.append(self.create_package_resource(url=source_of_data))
            if more_information:
                resources.append(self.create_package_resource(url=more_information))
            package = self.create_package(
                name=entity.pop('Unik identifikator'),
                title=entity.pop('Type data (tittel)', ''),
                url=source_of_data,
                maintainer=updated_by,
                author=updated_by,
                tags=['offentlig-sektors-data'],
                extras=entity,
                #license_id=license_id, # Post-licenses servization.
                license=license_title,   # Pre-licenses servization.
                resources=resources,
            )
        else:
            package = None
        return package

    def _old_entity_to_package(self, entity):
        """Makes a CKAN package from Norwegian Government spreadsheet entity."""
        if entity.get('Unique identifier', ''):
            package = self.create_package(
                name=entity.pop('Unique identifier'),
                title=entity.pop('Title (description)', ''),
                url=entity.pop('Url to source of data', ''),
                maintainer=entity.pop('Updated by', ''),
                author=entity.pop('Updated by', ''),
                notes=entity.pop('notes', ''),
                tags=['norwegian-government-data'],
                extras=entity,
            )
        else:
            package = None
        return package

if __name__ == '__main__':
    NorwegianGovernmentLoader().run()

