#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Script for importing nodes from yaml information generated by gformat.py
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#
from django.core.management.base import BaseCommand,CommandError
from django.db.utils import IntegrityError
from optparse import OptionParser, make_option
from gheat.models import *
import os
import sys
import logging
import yaml

from select import select
from collections import defaultdict

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


class Command(BaseCommand):
  args = '[<filename>]'
  help = 'Specify - to read from stdin'

  def handle(self, *args, **options):
    if len(args) == 0:
      self.print_help(sys.argv[0],sys.argv[1])
      raise CommandError("Not all arguments are provided")

    filename = args[0]
    timeout = 2
    if filename == '-':
      rlist, _, _ = select([sys.stdin], [], [], timeout)
      if rlist:
        fh = sys.stdin
      else:
       raise CommandError("No stdin input specified within %s seconds" % timeout)
    else:
      if not os.path.isfile(filename):
       raise CommandError("yaml file '%s' does not exists" % filename)
      fh = open(filename,'r')

    hosts = yaml.load(fh)
    for host,items in hosts.iteritems():
      node, created = Node.objects.get_or_create(name=host,
         latitude=items['latitude'],longitude=items['longitude'])
      if created:
        logger.info("Created Node '%s'" % node))
    logger.info("Processed %s items" % len(hosts))

