# -*- 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 karesansui
from karesansui.lib.const import VIRT_DISK_DIR, \
     VIRT_COMMAND_ADD_DISK, DISK_MIN_SIZE
from karesansui.lib.utils import uniq_filename, is_param, chk_create_disk
from karesansui.lib.checker import Checker, \
     CHECK_EMPTY, CHECK_VALID, CHECK_MIN, CHECK_MAX
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 JobGroup, Job

from pysilhouette.command import dict2command

# lib public
def validates_disk(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    # sparse

    # disk
    if is_param(obj.input, 'disk_size'):
        check = checker.check_number(_('Disk Size (MB)'),
                                     obj.input.disk_size,
                                     CHECK_EMPTY | CHECK_VALID | CHECK_MIN,
                                     min = DISK_MIN_SIZE,
                                     ) and check

        if chk_create_disk(VIRT_DISK_DIR, obj.input.disk_size) is False:
            check = False
            checker.add_error(_('Disk size is too large.'))
    else:
        check = False
        checker.add_error(_('"%s" is required.') % _('Disk Size (MB)'))

    obj.view.alert = checker.errors

    return check


def create_disk_job(obj, guest, name, sparse, disk_size, options={}):
    cmdname = u"Add disk"
    cmd = VIRT_COMMAND_ADD_DISK

    if not (sparse is None):
        options["sparse"] = None

    options['name'] = name
    options["size"] = disk_size
    options["disk"] = "%s/%s/%s.img" % (VIRT_DISK_DIR, name, uniq_filename())

    _cmd = dict2command(
        "%s/%s" % (karesansui.config['application.bin.dir'], cmd), options)

    _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
    _jobgroup.jobs.append(Job('%s command' % cmdname, 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
