# -*- 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 os

import web
import simplejson as json

import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.virt import KaresansuiVirtException, KaresansuiVirtConnection

from karesansui.db.access.snapshot import findby1, is_findby1_guestby1
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

class GuestBy1CurrentSnapshot(Rest):

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

        if is_param(self.input, 'id') is False \
            or is_int(self.input.id) is False:
            return web.badrequest("Request data is invalid.")

        snapshot_id = self.input.id

        if is_findby1_guestby1(self.orm, snapshot_id, guest_id) == 0:
            return web.badrequest("Request data is invalid.")

        snapshot = findby1(self.orm, snapshot_id)

        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(snapshot.machine.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
        finally:
            kvc.close()

        action_cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'],
                       VIRT_COMMAND_APPLY_SNAPSHOT),
            {"name" : domname, "id" : snapshot.name})

        cmdname = 'Apply Snapshot'

        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, action_cmd)
        _jobgroup.jobs.append(_job)

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

        self.view.currentsnapshot = snapshot

        return web.accepted(url=web.ctx.path)

urls = (
    '/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
    )
