#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Clean/Clear the cached tiles
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#
from django.core.management.base import BaseCommand, CommandError
from optparse import OptionParser, make_option
from gheat.models import TileCache
import datetime
import sys

class Command(BaseCommand):
  option_list = BaseCommand.option_list + (
    make_option('-d', '--datum', dest='datum', default=None, help="""Provide date
      in following format: %Y-%m-%d[-%H%M], to delete all time generated before
      this time the filename"""),)

  def handle(self, *args, **options):
    if options['datum'] == None:
       datum = datetime.datetime.now()
    else:
      # Try parsing different formats
      for fmt in ['%Y-%m-%d-%H%M', '%Y-%m-%d']:
        try:
          datum = datetime.datetime.strptime(options['datum'],fmt)
          break
        except ValueError:
          datum = None
      if not datum:
        raise CommandError("Invalid date '%s'\n" % options['datum'])

    obj = TileCache.objects.filter(creation_time__range=(datetime.datetime.fromtimestamp(0), datum))
    print "#INFO: Deleting '%s' objects" % obj.count()
    obj.delete()

