# -*- 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
from pkg_resources import resource_filename

import os
from subprocess import check_call ,CalledProcessError
from xml.dom.minidom import parseString
import libvirt
from ienocloud.libvirtutil import *
#from virtmonitor.libvirtutil import * 

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

  hostcnf={}
  storagecnf={}

  def __init__(self):
    self.hosturls = Configuration.getlist(self.config ,"virtmonitor" ,"host.urls" ,["qemu:///system"]);
    self.hostcnf['hosturls'] = self.hosturls
    self.hostcnf['imagedir'] = Configuration.get(self.config ,"virtmonitor" ,"host.imagedir" ,"/tmp");
    self.hostcnf['bridge'] = Configuration.get(self.config ,"virtmonitor" ,"host.bridge" ,"dmzbr");
    self.hostcnf['mac'] = Configuration.get(self.config ,"virtmonitor" ,"host.mac" ,'02:00:00:21:%02X:%02X');
    self.hostcnf['vnetdevice'] = Configuration.get(self.config ,"virtmonitor" ,"host.vnetdevice" ,"vnet");
    self.storagecnf['isoimages'] = Configuration.getlist(self.config ,"virtmonitor" ,"host.isoimages" ,['ubuntu', 'virtio'])
    self.storagecnf['targetname'] = Configuration.get(self.config ,"virtmonitor" ,"storage.targetname" ,"xxxxxxx");
    self.storagecnf['ip'] = Configuration.get(self.config ,"virtmonitor" ,"storage.ip" ,"127.0.0.1");
#    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'イーノックラウド', 'viewvm', '仮想マシン一覧')

  def render_admin_panel(self, req, cat, page, path_info):
    self.log.info("path_info:"+str(path_info))
    if path_info == None:
      hosts = []
      for i in range(0,len(self.hosturls)):
        c = libvirt.open(self.hosturls[i])
        domlist = []

        for id in c.listDomainsID():
          d = DomInfo(con=c,id=id,name=None)
          domlist.append(d)

        for name in c.listDefinedDomains():   
          d = DomInfo(con=c,id=None,name=name)
          domlist.append(d)  

      hosts.append({'hostid':i,'url':self.hosturls[i],'doms': domlist})
        
#      hosts = [{'hostid': 1, 'url':'qemu:///system','doms': [
#      {'name': "VMName", 'status': '停止中', 'vncport': 5901, 'ip': '192.168.1.1', 'cpu': 1, 'mem':0.5}
#      ]}]
      return 'admin_viewvmlist.html', {'hosts': hosts}
    else:
      (hostid, vm) = path_info.split('/')
      c = libvirt.open(self.hosturls[int(hostid)])
      d = DomInfo(con=c,id=None,name=vm)
#      storagecnf = {'isoimages': ['ubuntu','fedora','redhat','suse']}
#      dom = {'name': "VMName", 'status': '停止中', 'vncport': 5901, 'ip': '192.168.1.1', 'vcpu': 1, 'mem':0.5, 'disktype': 'raw', 'virtio': False, 'lun': 2}
      return 'admin_viewvm.html', {'dom': d, 'storagecnf': self.storagecnf, 'hosturl': self.hosturls[int(hostid)]}


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