# -*- coding: utf-8 -*-
from pyramid_oereb.lib.sources import BaseDatabaseSource
from pyramid_oereb.lib.sources.document import DocumentBaseSource
from pyramid_oereb import Config


class DatabaseSource(BaseDatabaseSource, DocumentBaseSource):

    def read(self, office_records):
        """
        Central method to read all theme entries.
        """
        session = self._adapter_.get_session(self._key_)
        try:
            results = session.query(self._model_).all()
            self.records = list()
            for result in results:
                office_record_match = None
                for office_record in office_records:
                    if office_record.identifier == result.office_id:
                        office_record_match = office_record_match
                        break
                self.records.append(
                    self._record_class_(
                        document_type=Config.get_document_type_by_code(
                            result.document_type
                        ),
                        index=result.index,
                        law_status=Config.get_law_status_by_code(
                            result.law_status
                        ),
                        title=result.title,
                        responsible_office=office_record,
                        published_from=result.published_from,
                        published_until=result.published_until,
                        text_at_web=result.text_at_web,
                        abbreviation=result.abbreviation,
                        official_number=result.official_number,
                        only_in_municipality=result.only_in_municipality,
                        article_numbers=None,
                        file=result.file,
                        identifier=result.id
                    )
                )
        finally:
            session.close()
