# 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 fcntl
import os

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

from passerelle.apps.family.models import GenericFamily


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            '-a',
            '--archive-file',
            dest='archive_file',
            help='Archive containing data files',
            default='exports_prcit.zip',
        )
        parser.add_argument(
            '-c', '--connector', dest='connector', help='Slug of the connector to import data into'
        )

    def handle(self, *args, **options):

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

        try:
            connector = GenericFamily.objects.get(slug=options['connector'])
        except GenericFamily.DoesNotExist:
            return

        storage = DefaultStorage()
        lock_filename = storage.path('family-%s/import-orleans-data.lock' % connector.id)
        try:
            fd = open(lock_filename, 'w')  # pylint: disable=consider-using-with
            fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            raise CommandError('Command already running.')

        try:
            archive_name = os.path.basename(options['archive_file'])
            with open(options['archive_file'], 'rb') as archive_fd:
                connector.archive.save(archive_name, File(archive_fd))
        except Exception as e:
            raise CommandError('Error occured: %s' % e)
        finally:
            fd.close()
            os.unlink(lock_filename)
