import datetime
import os
import time
import xlrd
import csv
import re

from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError, transaction
from geopy import geocoders
from olcc.models import Product, ProductPrice, Store
from optparse import make_option

IMPORT_TYPES = ('csv_prices', 'prices', 'stores',)

class Command(BaseCommand):
    """
    This command parses an Excel spreadsheet containing OLCC product
    and price data and imports it into the database.
    """
    args = "<filename>"
    help = "Parses an excel document of OLCC price data."

    option_list = BaseCommand.option_list + (
        make_option('--quiet', action='store_true', dest='quiet',
            default=False, help='Suppress all output except errors'),
        make_option('--import-type', choices=IMPORT_TYPES,
            dest='import_type', default='prices',
            help='One of the following: %s' % (', '.join(IMPORT_TYPES),)),
        make_option('--geocode', action='store_true', dest='geocode',
            default=True, help='Geocode store addresses')
    )

    def uprint(self, msg):
        """
        Unbuffered print.
        """
        if not self.quiet:
            self.stdout.write("%s\n" % msg)
            self.stdout.flush()

    @transaction.commit_on_success
    def product_from_row(self, row):
        """
        Import a row of product price data as a new product record. The row data
        should correspond to a numeric price list file.

        :param row: A dict of keys mapped to row values.
        :return: A tuple containing a Product instance and a boolean indicating
                 if the Product record was newly created.
        """
        product = None
        created = False

        if Product.is_code_valid(row.get('code')):
            product, created = Product.objects.get_or_create(code=row.get('code'))

            if created:
                # Set the product title once and once only
                product.title = row.get('title')

            # Update our product
            if row.get('status'):
                product.status = row.get('status')
            if row.get('size'):
                product.size = row.get('size')
            if row.get('per_case'):
                product.bottles_per_case = int(float(row.get('per_case')))
            if row.get('proof'):
                product.proof = row.get('proof')
            if row.get('age'):
                # example values: '14 YRS', '1 YR', '8 MOS'
                m = re.search('(\\d+) (YRS?|MOS?)', row.get('age'))
                if m.group(2).startswith('MO'):
                    product.age = int(float(m.group(1))) / 12
                elif m.group(2).startswith('YR'):
                    product.age = m.group(1)