#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Script for importing nodes from yaml information generated by gformat.py
#
# Example: $ ~/wleiden/node-config/genesis/tools/gformat.py  full-export |
# ./manage.py import_nodes -
#
# 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'
  option_list = BaseCommand.option_list + (
    make_option('-g', '--debug', dest='debug', default='False', help="Debug", action="store_true"),
  )

  def handle(self, *args, **options):
    if options['debug']:
      logger.setLevel(logging.DEBUG)
    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():
      for iface_key in [x for x in items.keys() if x.startswith('iface_')]:
        if items[iface_key].has_key('ssid'):
          org = Organization.get_by_ssid(items[iface_key]['ssid'])
          if org: break
          logger.error("NO Organization for SSID '%s'", items[iface_key]['ssid'])

      if not org:
        logger.warning("NO Organization for Node '%s'", host)

      node, created = Node.objects.get_or_create(name=host)
      node.latitude = items['latitude']
      node.longitude = items['longitude']
      node.organization = org
      node.save()
      if created:
        logger.info("Created Node '%s'", node)
    logger.info("Processed %s items", len(hosts))

