# passerelle - uniform access to multiple data sources 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 argparse
import os

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

from passerelle.apps.csvdatasource.models import CsvDataSource


class Command(BaseCommand):
    help = 'change CSV file'

    def add_arguments(self, parser):
        parser.add_argument('slug')
        parser.add_argument('csv_file', type=argparse.FileType('rb'))
        parser.add_argument('--sheet-name', default=None)

    def handle(self, slug, csv_file, **options):
        try:
            instance = CsvDataSource.objects.get(slug=slug)
        except CsvDataSource.DoesNotExist:
            raise CommandError('csvdatasource %r does not exist' % slug)
        instance.csv_file = File(csv_file, name=os.path.basename(csv_file.name))
        if options['sheet_name']:
            instance.sheet_name = options['sheet_name']
        instance.save()
