from __future__ import unicode_literals
from db import connect
from clientjob.model import Job
from decorators import pi18n
from utils import adquire_thread_orm
import web

class DiskCurrentStateJob(Job):
    '''
    This job is sent when the user wants to see the partitions of a
    computer. The reply will have the next format:
    # TODO
    This reply will be used by CurrentStateDisk view to show to the
    user this information.
    '''

    __command__ = 'listDisk'

    def __init__(self, image):
        Job.__init__(self, self.__command__)

    @pi18n
    def get_user_message(self):
        '''
        We show a better message when the job is finished.
        For 15 minutes the message will have a link to the view
        where the images will be created. After of that 15 minutes
        the link won't appear any more to avoid, more than possible,
        unexpected behavior.
        '''
        if self.status != 'FINISHED':
            Job.get_user_message(self)

        # WARNING! web.ctx.plugin_manager is not available in the server daemon
        if self.status != 'FINISHED' or not hasattr(web.ctx, 'plugin_manager'):
            return Job.get_user_message(self)

        image_disk = web.ctx.plugin_manager.get_plugin_by_name('image_disk')

        return _('Retrieved the <a href=\"%s\">current disk state %s</a>') %\
            (image_disk.get_view_disk_state_url(self.id),
                    self.computer.name)

class CreateImageJob(Job):
    '''
    This job is sent when the user want create a image from a computer's
    partition. A image is given in the constructor, when the job is finished
    correctly so the image is added definitively in the database.
    '''
    __command__ = 'RestoreImage'

    def __init__(self, args, image_id, orm = None):
        command = self.__command__ + args
        Job.__init__(self, command)
        self.image_id = image_id

    @pi18n
    def get_user_message(self):
        if self.status != 'FINISHED':
            Job.get_user_message(self)

        return _('<a href=\"%s\">The image</a>was created sucessfully.') %\
                web.ctx.plugin_manager.get_plugin_by_name('diskimage').\
                get_edit_image_by_id_url(self.image_id)

    def update(self):
        orm = adquire_thread_orm()
        image = orm.query(Image).filter(Image.id == self.image_id).one()

        if self.status == 'FINISHED':
            image.created = True
            orm.commit()

        elif self.status in ('TIMEOUT', 'CANCELLED', 'ERROR'):
            orm.delete(image)
