# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009 HDE, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#

import web

import karesansui
from karesansui.lib.rest import Rest, auth

from karesansui.lib.const import VIRT_COMMAND_DELETE_DISK
from karesansui.lib.virt.virt import KaresansuiVirtException, \
     KaresansuiVirtConnection
from karesansui.lib.merge import MergeGuest
from karesansui.lib.utils import is_int

from karesansui.db.access.machine import findbyguest1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup

from pysilhouette.command import dict2command

# lib public
def delete_disk_job(obj, guest, name, target, options={}):
    options['name'] = name
    options['target'] = target

    _cmd = dict2command(
        "%s/%s" % (karesansui.config['application.bin.dir'], VIRT_COMMAND_DELETE_DISK), options)
        
    _jobgroup = JobGroup('Delete disk', karesansui.sheconf['env.uniqkey'])
    _jobgroup.jobs.append(Job('Delete disk', 0, _cmd))

    _machine2jobgroup = m2j_new(machine=guest,
                                jobgroup_id=-1,
                                uniq_key=karesansui.sheconf['env.uniqkey'],
                                created_user=obj.me,
                                modified_user=obj.me,
                                )
    
    save_job_collaboration(obj.orm,
                           obj.pysilhouette.orm,
                           _machine2jobgroup,
                           _jobgroup,
                           )        
    return True


class GuestBy1DiskBy1(Rest):
    
    @auth
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: web.notfound()
        
        if is_int(param[2]) is False:
            return web.badrequest()
        
        
        disk_id = int(param[2])
        
        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()

        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)

            virt = kvc.search_kvg_guests(domname)[0]
            
            guest = MergeGuest(model, virt)
            self.view.guest = guest
            self.view.disk_info = virt.get_disk_info()[disk_id]
        finally:
            kvc.close()
            
        return True

    """
    @auth
    def _PUT(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: web.notfound()

        if is_int(param[2]) is False:
            return web.badrequest()

        disk_id = int(param[2])

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
        finally:
            kvc.close()

        return web.accepted()
    """
    
    @auth
    def _DELETE(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: web.notfound()

        if is_int(param[2]) is False:
            return web.badrequest()

        disk_id = int(param[2])

        model = findbyguest1(self.orm, guest_id)
        if not model: return web.notfound()

        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            disk_info = virt.get_disk_info()[disk_id]
        finally:
            kvc.close()
            
        target = disk_info["target"]["dev"]
        self.logger.debug('spinning off delete_disk_job dom=%s, target=%s' % (domname, target))
        
        if delete_disk_job(self,model,domname,target) is True:
            return web.accepted()
        else:
            return False

urls = (
    '/host/(\d+)/guest/(\d+)/disk/(\d+)/?(\.part|\.json)?$', GuestBy1DiskBy1,
    )
