# -*- coding: utf-8 -*-
from trac.admin import IAdminPanelProvider
from trac.core import *
from trac.web.chrome import ITemplateProvider
from genshi.template import TemplateLoader
from trac.config import Configuration
#import libvirt
#from virtmonitor.libvirtutil import * 
from ienocloud.libvirtutil import *

import re
import os
from subprocess import check_call ,CalledProcessError
from pkg_resources import resource_filename
from xml.dom.minidom import parseString


class CreateVM(Component):
  implements(IAdminPanelProvider, ITemplateProvider)

  hostcnf={}
  storagecnf={}

  def __init__(self):
#    self.hosturls = Configuration.getlist(self.config ,"ienocloud" ,"host.urls" ,["qemu+ssh://root@192.168.1.2/system","qemu+ssh://root@127.0.0.1/system"]);
    self.hosturls = Configuration.getlist(self.config ,"ienocloud" ,"host.urls" ,["qemu:///system","qemu+ssh://root@192.168.1.2/system"]);
    self.hostcnf['hosturls'] = self.hosturls
    self.hostcnf['imagedir'] = Configuration.get(self.config ,"ienocloud" ,"host.imagedir" ,"/tmp");
    self.hostcnf['bridge'] = Configuration.get(self.config ,"ienocloud" ,"host.bridge" ,"dmzbr");
    self.hostcnf['mac'] = Configuration.get(self.config ,"ienocloud" ,"host.mac" ,'02:00:21:00:%02X:%02X');
    self.hostcnf['vnetdevice'] = Configuration.get(self.config ,"ienocloud" ,"host.vnetdevice" ,"vnet");

#      host = {
#        'address':'192.168.1.2',
#        'imagedir': '/tmp',
#        'bridge':"dmzbr0",
#        'vnetdevice':"vnet",
#        'mac': "00:03:04:%02X:%02X"
#      }

    self.storagecnf['isoimages'] = Configuration.getlist(self.config ,"ienocloud" ,"host.isoimages" ,['ubuntu', 'virtio'])
    self.storagecnf['targetname'] = Configuration.get(self.config ,"ienocloud" ,"storage.targetname" ,"xxxxxxx");
    self.storagecnf['address'] = Configuration.get(self.config ,"ienocloud" ,"storage.address" ,"127.0.0.1");
    self.storagecnf['port'] = Configuration.get(self.config ,"ienocloud" ,"storage.port" ,"3260");
#    lunmap = Configuration.getlist(self.config ,"virtmonitor" ,"storage.ip" ,["","puppy","ubuntu"]);

#    hostcnf['imagedir'] = '/tmp'
#    hostcnf['bridge'] = 'dmzbr'
#    hostcnf['mac'] = '02:00:00:21:%02X:%02X'
#    hostcnf['vnetdevice'] = 'vnet'
#    storagecnf['ip'] = '192.168.1.7'
#    storagecnf['targetname'] = '192.168.1.7'

  # 初期化コード
  # IAdminPanelProvider
  def get_admin_panels(self,req):
    # パーミッション制御
    yield ('cloud', u'イーノックラウド', 'createvm', '仮想マシン作成')

  def render_admin_panel(self, req, cat, page, path_info):
    
    self.log.info("path_info="+str(path_info))
#    if path_info and path_info.startswith("createvm/"):
    if req.args.get('create')!=None:
      vm={}
      name = req.args.get('name')
      virtio = True if req.args.get('virtio')=="True" else False
      vcpu = int(req.args.get('vcpu'))
      mem = float(req.args.get('mem'))
      drivertype = req.args.get('drivertype')
      hostid = int(req.args.get('hostid'))
      hddsize = float(req.args.get('hddsize'))
      lunid = req.args.get('lunid')
      if lunid=='-':
        lunid = None
#      host = {
#        'address':'192.168.1.2',
#        'imagedir': '/tmp',
#        'bridge':"dmzbr0",
#        'vnetdevice':"vnet",
#        'mac': "00:03:04:%02X:%02X"
#      }

#      storage = {
#        'ip': '192.168.2.8',
#        'port': 3260,
#        'targetname': 'iqn.iscsi',
#      }

      dom = DomInfo(name=name,id=1,hostid=hostid,vcpu=vcpu,virtio=virtio,mem=mem,drivertype=drivertype,hddsize=hddsize, lun=lunid)
      self.log.info(dom.createXML(hostcnf=self.hostcnf, storagecnf=self.storagecnf))
#      connection = libvirt.open(hosturls[hostid])
      dom.create(self.hosturls[hostid], hostcnf=self.hostcnf ,storagecnf=self.storagecnf)
      

#      hosturl = self.hosturls[vm['hostid']]
#      self.log.info("vm:"+str(vm))
#      con = libvirt.open(hosturl)
#      vm['id'] = getAvailableVMID(con)
#      createVM(con, hostcnf, vm, storagecnf)	
#      vm['id'] = 2
#      log.self.info(createXML(hostcnf, vm, storagecnf))
#      req.redirect(req.href.chrome()+"/admin/cloud/viewvm")
      req.redirect(req.href("/admin/cloud/viewvm/%s/%s" % (hostid,dom.name)))
#      return 'admin_createvm.html', {'hostcnf': self.hostcnf,'storagecnf':self.storagecnf,'vm':vm} 
    else: 
      return 'admin_createvm.html', {'hostcnf': self.hostcnf,'storagecnf':self.storagecnf} 

  # ITemplateProvider
  def get_htdocs_dirs(self):
    return []
  def get_templates_dirs(self):
    return [resource_filename('ienocloud', 'templates')]
