# Path: findingaids/fa/models.py
# class Archive(models.Model):
#     '''Model to define Archives associated with EAD documents, for use with
#     admin user permissions and to identify subversion repositories where
#     content will be published from.'''
#     label = models.CharField(max_length=10,
#         help_text='Short label to identify an archive')
#     name = models.CharField(max_length=255,
#         help_text='repository name (subarea) in EAD to identify finding aids associated with this archive')
#     svn = models.URLField('Subversion Repository',
#         help_text='URL to subversion repository containing EAD for this archive')
#     slug = models.SlugField(help_text='''shorthand id
#         (auto-generated from label; do not modify after initial archive definition)''')
#     contacts = models.ManyToManyField(settings.AUTH_USER_MODEL,
#         help_text='Contact person for display on the Request Materials page (email required)',
#         blank=True)
# 
# 
#     def __unicode__(self):
#         return self.label
# 
#     @property
#     def svn_local_path(self):
#         return os.path.join(settings.SVN_WORKING_DIR, self.slug)
# 
#     def contact_names(self):
#         '''List of contact names method for display in django admin list
#         display.  Shows email if user has no full name.'''
#         return ', '.join([contact.get_full_name() or contact.email
#                           for contact in self.contacts.all()])
#     contact_names.short_description = "Contacts"
# 
# Path: findingaids/fa_admin/models.py
# class EadFile(object):
#     """Information about an EAD file available to be published or previewed."""
#     def __init__(self, filename, modified, archive=None):
#         self.filename = filename
#         self.mtime = modified
#         self.modified = datetime.utcfromtimestamp(modified)
#         self._published = None
#         self._previewed = None
#         self.archive = archive
# 
#     def __repr__(self):
#         return '<%s %s>' % (self.__class__, self.filename)
# 
#     def get_published(self):
#         "Date object was modified in eXist, if published"
#         # TODO: previewed & published logic substantially the same; consolidate
#         if self._published is None:
#             try:
#                 fa = get_findingaid(filter={'document_name': self.filename},
#                                        only=['last_modified'])
#                 if fa.count():
#                     self._published = fa[0].last_modified
#             except Exception:
#                 # FIXME: distinguish between not found and eXist error?
#                 pass
# 
#             # not found or error - store so we don't look it up again
#             if self._published is None:
#                 self._published = False
#         return self._published
# 
#     def set_published(self, value):
#         if value is None:
#             self._published = False  # store to prevent xquery lookup
#         else:
#             self._published = value
# 
#     published = property(get_published, set_published)
# 
#     def get_previewed(self):
#         """Date object was loaded to eXist preview collection, if currently
#             available in preview."""
#         if self._previewed is None:
#             try:
#                 fa = get_findingaid(filter={'document_name': self.filename},
#                                        only=['last_modified'], preview=True)
#                 if fa.count():
#                     self._previewed = fa[0].last_modified
#             except Exception:
#                 pass
# 
#             # not found or error - store so we don't look up again
#             if self._previewed is None:
#                 self._previewed = False
#         return self._previewed
# 
#     def set_previewed(self, value):
#         if value is None:
#             self._previewed = False  # store to prevent xquery lookup
#         else:
#             self._previewed = value
# 
#     previewed = property(get_previewed, set_previewed)


import os
import shutil
import tempfile
import time
from django.test import TestCase
from mock import patch, Mock
from findingaids.fa.models import Archive
from findingaids.fa_admin.models import EadFile
from findingaids.fa_admin.source import recent_xml_files, svn_xml_files, \
    files_to_publish
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp('findingaids-recentfiles-test')
        # create xml files to list
        self.tmpfiles = []
        for num in ['first', 'second', 'third']:
            self.tmpfiles.append(tempfile.NamedTemporaryFile(suffix='.xml',
                    prefix=num + '_', dir=self.tmpdir, delete=False))
            time.sleep(1)        # ensure modification times are different
        # add a non-xml file
        self.nonxml_tmpfile = tempfile.NamedTemporaryFile(suffix='.txt',
                    prefix='nonxml', dir=self.tmpdir, delete=False)

    def tearDown(self):
        # clean up temp files & dir
        shutil.rmtree(self.tmpdir)

    def test_recent_xml_files(self):
        recent_xml = recent_xml_files(self.tmpdir)
        self.assertEqual(3, len(recent_xml))
        # should be in reverse order - last created first
        self.assertEqual(recent_xml[0].filename, os.path.basename(self.tmpfiles[2].name))
        self.assertEqual(recent_xml[1].filename, os.path.basename(self.tmpfiles[1].name))
        self.assertEqual(recent_xml[2].filename, os.path.basename(self.tmpfiles[0].name))
        # non-xml file not included
        filenames = [eadfile.filename for eadfile in recent_xml]
        self.assert_(os.path.basename(self.nonxml_tmpfile.name) not in filenames)


class SvnXmlFilesTest(TestCase):


# Path: findingaids/fa/models.py
# class Archive(models.Model):
#     '''Model to define Archives associated with EAD documents, for use with
#     admin user permissions and to identify subversion repositories where
#     content will be published from.'''
#     label = models.CharField(max_length=10,
#         help_text='Short label to identify an archive')
#     name = models.CharField(max_length=255,
#         help_text='repository name (subarea) in EAD to identify finding aids associated with this archive')
#     svn = models.URLField('Subversion Repository',
#         help_text='URL to subversion repository containing EAD for this archive')
#     slug = models.SlugField(help_text='''shorthand id
#         (auto-generated from label; do not modify after initial archive definition)''')
#     contacts = models.ManyToManyField(settings.AUTH_USER_MODEL,
#         help_text='Contact person for display on the Request Materials page (email required)',
#         blank=True)
# 
# 
#     def __unicode__(self):
#         return self.label
# 
#     @property
#     def svn_local_path(self):
#         return os.path.join(settings.SVN_WORKING_DIR, self.slug)
# 
#     def contact_names(self):
#         '''List of contact names method for display in django admin list
#         display.  Shows email if user has no full name.'''
#         return ', '.join([contact.get_full_name() or contact.email
#                           for contact in self.contacts.all()])
#     contact_names.short_description = "Contacts"
# 
# Path: findingaids/fa_admin/models.py
# class EadFile(object):
#     """Information about an EAD file available to be published or previewed."""
#     def __init__(self, filename, modified, archive=None):
#         self.filename = filename
#         self.mtime = modified
#         self.modified = datetime.utcfromtimestamp(modified)
#         self._published = None
#         self._previewed = None
#         self.archive = archive
# 
#     def __repr__(self):
#         return '<%s %s>' % (self.__class__, self.filename)
# 
#     def get_published(self):
#         "Date object was modified in eXist, if published"
#         # TODO: previewed & published logic substantially the same; consolidate
#         if self._published is None:
#             try:
#                 fa = get_findingaid(filter={'document_name': self.filename},
#                                        only=['last_modified'])
#                 if fa.count():
#                     self._published = fa[0].last_modified
#             except Exception:
#                 # FIXME: distinguish between not found and eXist error?
#                 pass
# 
#             # not found or error - store so we don't look it up again
#             if self._published is None:
#                 self._published = False
#         return self._published
# 
#     def set_published(self, value):
#         if value is None:
#             self._published = False  # store to prevent xquery lookup
#         else:
#             self._published = value
# 
#     published = property(get_published, set_published)
# 
#     def get_previewed(self):
#         """Date object was loaded to eXist preview collection, if currently
#             available in preview."""
#         if self._previewed is None:
#             try:
#                 fa = get_findingaid(filter={'document_name': self.filename},
#                                        only=['last_modified'], preview=True)
#                 if fa.count():
#                     self._previewed = fa[0].last_modified
#             except Exception:
#                 pass
# 
#             # not found or error - store so we don't look up again
#             if self._previewed is None:
#                 self._previewed = False
#         return self._previewed
# 
#     def set_previewed(self, value):
#         if value is None:
#             self._previewed = False  # store to prevent xquery lookup
#         else:
#             self._previewed = value
# 
#     previewed = property(get_previewed, set_previewed)


# Path: findingaids/fa_admin/tests/source.py
import os
import shutil
import tempfile
import time
from django.test import TestCase
from mock import patch, Mock
from findingaids.fa.models import Archive
from findingaids.fa_admin.models import EadFile
from findingaids.fa_admin.source import recent_xml_files, svn_xml_files, \
    files_to_publish

    def setUp(self):
        self.tmpdir = tempfile.mkdtemp('findingaids-recentfiles-test')
        # create xml files to list
        self.tmpfiles = []
        for num in ['first', 'second', 'third']:
            self.tmpfiles.append(tempfile.NamedTemporaryFile(suffix='.xml',
                    prefix=num + '_', dir=self.tmpdir, delete=False))
            time.sleep(1)        # ensure modification times are different
        # add a non-xml file
        self.nonxml_tmpfile = tempfile.NamedTemporaryFile(suffix='.txt',
                    prefix='nonxml', dir=self.tmpdir, delete=False)

    def tearDown(self):
        # clean up temp files & dir
        shutil.rmtree(self.tmpdir)

    def test_recent_xml_files(self):
        recent_xml = recent_xml_files(self.tmpdir)
        self.assertEqual(3, len(recent_xml))
        # should be in reverse order - last created first
        self.assertEqual(recent_xml[0].filename, os.path.basename(self.tmpfiles[2].name))
        self.assertEqual(recent_xml[1].filename, os.path.basename(self.tmpfiles[1].name))
        self.assertEqual(recent_xml[2].filename, os.path.basename(self.tmpfiles[0].name))
        # non-xml file not included
        filenames = [eadfile.filename for eadfile in recent_xml]
        self.assert_(os.path.basename(self.nonxml_tmpfile.name) not in filenames)


class SvnXmlFilesTest(TestCase):


    @patch('findingaids.fa_admin.source.wc')