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

import logging
from pysilhouette.db.access import \
    jobgroup_findbyall, jobgroup_findbyall_limit, jobgroup_findbystatus, \
    jobgroup_findbyuniqkey, jobgroup_findbyid, jobgroup_update, \
    job_findbyjobgroup_id, job_update, job_result_action, job_result_rollback, \
    get_progress, up_progress, \
    save as jg_save, update as jg_update, delete as jg_delete

from karesansui.db.model._2pysilhouette import Job, JobGroup
from karesansui.db.access import dbsave, dbupdate, dbdelete
import karesansui.db.access.search
import karesansui.db.access.machine2jobgroup

logger = logging.getLogger('karesansui.db.access._2pysilhouette')

def jg_findbyall(session, jobgroup_ids=None, status=None, desc=False):
    
    query = session.query(JobGroup)

    if not jobgroup_ids is None:
        query = query.filter(JobGroup.id.in_(jobgroup_ids))

    if not status is None:
        query = query.filter(JobGroup.status == status)

    if desc is True:
        return query.order_by(JobGroup.id.desc()).all()
    else:
        return query.order_by(JobGroup.id.asc()).all()
        

def jg_findby1(session, jobgroup_id):
    return session.query(JobGroup).filter(JobGroup.id == jobgroup_id).first()

def jg_findbylimit(session, limit, desc=False):
    if desc is True:
        return session.query(JobGroup).order_by(JobGroup.id.desc()).all()[:limit]
    else:
        return session.query(JobGroup).order_by(JobGroup.id.asc()).all()[:limit]

def jobgroup_findbyuniqkey_limit(session, uniq_key, limit, desc=False):
    if uniq_key:
        if desc is True:
            return session.query(JobGroup).filter(JobGroup.uniq_key == uniq_key).order_by(JobGroup.id.desc()).all()[:limit]
        else:
            return session.query(JobGroup).filter(JobGroup.uniq_key == uniq_key).order_by(JobGroup.id.asc()).all()[:limit]
    else:
        return None

def save_job_collaboration(karesansui_session,
                           pysilhouette_session,
                           machine2jobgroup,
                           jobgroup):
    """<comment-ja>
    ジョブの登録を行う。
      - PySilhouette:JobgroupテーブルとKaresansui:machine2jobgroupテーブルに
      登録を行います。
    @param karesansui_session: Karesansui Database Session
    @type karesansui_session: Session
    @param pysilhouette_session: Pysilhouette Database Session
    @type pysilhouette_session: Session
    @param machine2jobgroup: Table Model(Karesansui)
    @type machine2jobgroup: karesansui.db.model.machine2jobgroup.Machine2Jobgroup
    @param jobgroup: Table Model(PySilhouette)
    @type jobgroup: pysilhouette.db.model.JobGroup
    @return 
    </comment-ja>
    <comment-en>
    TODO: English Comment
    </comment-en>
    """
    # JobGroup INSERT
    jg_save(pysilhouette_session, jobgroup)
    pysilhouette_session.commit()
    
    # Machine2JobGroup INSERT
    try:
        machine2jobgroup.jobgroup_id = jobgroup.id
        karesansui.db.access.machine2jobgroup.save(karesansui_session, machine2jobgroup)
        karesansui_session.commit()
    except:
        try:
            jg_delete(pysilhouette_session, jobgroup)
            pysilhouette_session.commit()
        except:
            # rollback(jobgroup)
            logger.critical('Failed to register the JobGroup. #6 - jobgroup id=%d' \
                              % jobgroup.id)
        raise # throw


if __name__ == '__main__':
    pass
