# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution Addon
#    Copyright (C) 2009-2013 IRSID (<http://irsid.ru>),
#    Paul Korotkov (korotkov.paul@gmail.com).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import osv, fields
from core import *

class edu_order(osv.Model):
    _name = 'edu.order'
    _description = 'Academic Order'
    _inherit = 'edu.doc'
    _rec_name = 'code'
    _track = {
        'state': {
            'irsid_edu.mt_order_updated': lambda self, cr, uid, obj, ctx=None: True,
        },
    }
# Naming Functions
    def name_get(self, cr, uid, ids, context=None):
        if not len(ids):
            return []
        res = []
        for order in self.browse(cr, uid, ids, context=context):
            res.append((order.id, order.code + ': ' + order.name))
        return res

    def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
        if not args:
            args = []
        if context is None:
            context = {}
        ids = self.search(cr, user, [
            '|',('code','ilike',name),('name','ilike',name),
            ] + args, li
mit=limit, context=context)
        return self.name_get(cr, user, ids, context=context)
# Workflow Functions
    def set_draft(self, cr, uid, ids, context=None):
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.i
d, {
                'state': 'draft',
                'date_approved': False,
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_draft(cr, uid, line_ids, context=context)
        return True

    def set_confirmed(self, cr, uid, ids, context=None):
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.id, {
                'state': 'confirmed',
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_confirmed(cr, uid, line_ids, context=context)
        return True

    def set_validated(self, cr, uid, ids, context=None):
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.id, {
                'state': 'validated',
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_validated(cr, uid, line_ids, context=context)
        return True

    def set_approved(self, cr, uid, ids, context=None):
        if isinstance(ids, (int, long)):
            ids = [ids]
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.id, {
                'state': 'approved',
                'date_approved': fields.date.context_today(self, cr, uid, context=context),
                'user_approved': uid,
                'code': order.code =='/' and self.pool.get('ir.sequence').get(cr, uid, 'edu.order') or order.code or '/'
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_approved(cr, uid, line_ids, context=context)
        lines = line_obj.browse(cr, uid, line_ids, context=context)
        st_program_obj = self.pool.get('edu.student.program')
        for line in lines:
            if line.type != 'other':
                st_program_id = line.st_program_id.id
                if not st_program_id:
                    st_program_ids = st_program_obj.search(cr, uid, [('student_id','=', line.student_id.id),('program_id','=',line.program_id.id)], context=context)
                    if st_program_ids:
                        st_program_id = st_program_ids[0]
                    else:
                        vals = st_program_obj.onchange_program_id(cr, uid, ids, line.program_id.id, context=context)['value']
                        vals['student_id'] = line.student_id.id
                        vals['program_id'] = line.program_id.id
                        st_program_id = st_program_obj.create(cr, uid, vals, context=context)
                st_program = st_program_obj.browse(cr, uid, st_program_id, context=context)
                st_program_obj.write(cr, uid, st_program_id,{
                    'program_id': line.program_id.id or st_program.program_id.id,
                    'stage_id': line.stage_id.id or st_program.stage_id.id,
                    'plan_id': line.plan_id.id or st_program.plan_id.id,
                    'status': line.status or st_program.status,
                }, context=context)
        return True

    def set_done(self, cr, uid, ids, context=None):
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.id, {
                'state': 'done',
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_done(cr, uid, line_ids, context=context)
        return True

    def set_canceled(self, cr, uid, ids, context=None):
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.id, {
                'state': 'canceled',
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_canceled(cr, uid, line_ids, context=context)
        return True

    def set_rejected(self, cr, uid, ids, context=None):
        for order in self.browse(cr, uid, ids, context=context):
            self.write(cr, uid, order.id, {
                'state': 'rejected',
            }, context=context)
        line_obj = self.pool.get('edu.order.line')
        line_ids = line_obj.search(cr, uid, [('order_id', 'in', ids)], context=context)
        line_obj.set_rejected(cr, uid, line_ids, context=context)
        return True

    def make_work_orders(self, cr, uid, ids, context=None):
        work_order_obj = self.pool.get('edu.work.order')
        work_obj = self.pool.get('edu.work')
        module_work_obj = self.pool.get('edu.module.work')
        line_obj = self.pool.get('edu.order.line')
        cr.execute("""
            SELECT DISTINCT
                year_id,
                program_id,
                stage_id
            FROM
                edu_order_line
            WHERE
                order_id IN %s AND
                type = 'transfer'
        """,(tuple(ids),))
        params = cr.fetchall()
        if params:
            for param in params:
                cr.execute("""
                    SELECT DISTINCT
                        module_id
                    FROM
                        edu_plan_module_rel
                    WHERE
                        plan_id IN (
                            SELECT DISTINCT
                                plan_id
                            FROM
                                edu_order_line
                            WHERE
                                order_id IN %s AND
               