# Passerelle - uniform access to data and services
# Copyright (C) 2017  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import zipfile
import tempfile
import fcntl
from optparse import make_option

from django.core.files.base import File
from django.core.management.base import BaseCommand, CommandError

from family.models import GenericFamily

LOCK_FILENAME = os.path.join(tempfile.gettempdir(), 'import-orleans-data.lock')


class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('-a', '--archive-name', dest='archive_name',
                    help="""Archive name containing data files""",
                    default='exports_prcit.zip'
        ),
        make_option('-d', '--data-directory', dest='data_dir',
                    help="""Directory containing archive and invoice files"""
        ),
        make_option('-c', '--connector', dest='connector',
                    help="""Slug of the connector to import data into"""
        )
    )

    def handle(self, *args, **options):
        if not options['data_dir']:
            raise CommandError('No data dir specified.')

        if not os.path.exists(options['data_dir']):
            raise CommandError('Directory %s does not exist.' % options['data_dir'])

        archive_path = os.path.join(options['data_dir'], options['archive_name'])

        if not os.path.exists(archive_path):
            raise CommandError('File %s does not exist.' % archive_path)

        try:
            connector = GenericFamily.objects.get(slug=options['connector'])
        except GenericFamily.DoesNotExist:
            return
        try:
            fd = open(LOCK_FILENAME, 'w')
            fcntl.lockf(fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
            invoices_dir = os.path.join(options['data_dir'], 'factures')
            with zipfile.ZipFile(archive_path, 'a') as archive:

                for invoice_file in os.listdir(invoices_dir):
                    if invoice_file.startswith('facture_'):
                        archive.write(os.path.join(invoices_dir, invoice_file),
                                      'invoices/%s' % invoice_file)
            connector.archive.save(options['archive_name'], File(file(archive_path)))
        except IOError:
            raise CommandError('Command already running.')
        except Exception, e:
            raise CommandError('Error occured: %s' % e)
        finally:
            fd.close()
            os.unlink(LOCK_FILENAME)
