# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution, third party addon
#    Copyright (C) 2004-2015 Vertel AB (<http://vertel.se>).
#
#    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 import models, fields, api, _
from openerp.exceptions import except_orm, Warning, RedirectWarning
import logging
_logger = logging.getLogger(__name__)
class smart_salary_simulator_payslip(models.Model):
    _inherit = 'hr.payslip'
    
    def simulate_payslip(self, uid, salary, values):
        user = self.env['res.users'].browse(uid)[0]
        if user.employee_ids and user.employee_ids[0].contract_ids:
            employee = user.employee_ids[0]
            contract = employee.contract_ids[0]
        else:
            employee = self.env.ref('smart_salary_simulator_se.dummy_employee')
            contract = self.env.ref('smart_salary_simulator_se.smart_contract_swe')
        
        payslip = self.create({
            'struct_id': contract.struct_id.id,
            'employee_id': employee.id,
            'date_from': fields.Date.today(),
            'date_to': fields.Date.today(),
            'state': 'draft',
            'contract_id': contract.id,
            'input_line_ids': [
                (0, _, {
                    'name': 'Salary Base',
                    'code': 'SALARY',
                    'contract_id': contract.id,
                    'amount': salary,
                }),
                
                #~ (0, _, {
                    #~ 'name': 'Invoice VAT',
                    #~ 'code': 'VAT',
                    #~ 'contract_id': contract.id,
                    #~ 'amount': values['vat'],
                #~ }),
                #~ (0, _, {
                    #~ 'name': 'Smart Share',
                    #~ 'code': 'SMARTSHARE',
                    #~ 'contract_id': contract.id,
                    #~ 'amount': values['smart_fee'],
                #~ }),
                #~ (0, _, {
                    #~ 'name': 'Expenses',
                    #~ 'code': 'EXPENSES',
                    #~ 'contract_id': contract.id,
                    #~ 'amount': values['expenses'],
                #~ }),
                #~ (0, _, {
                    #~ 'name': 'Expenses VAT',
                    #~ 'code': 'EXPVAT',
                    #~ 'contract_id': contract.id,
                    #~ 'amount': values['expenses'],
                #~ }),
                (0, _, {
                    'name': 'Year of Birth',
                    'code': 'YOB',
                    'contract_id': contract.id,
                    'amount': values['yob'],
                }),
                (0, _, {
                    'name': 'Current Year',
                    'code': 'YEAR',
                    'contract_id': contract.id,
                    'amount': fields.Date.from_string(fields.Date.today()).year,
                }),
                (0, _, {
                    'name': 'Musician',
                    'code': 'MUSICIAN',
                    'contract_id': contract.id,
                    'amount': 1 if values['musician'] == 'on' else 0,
                }),
                (0, _, {
                    'name': 'Withholding Tax Rate',
                    'code': 'WT',
                    'contract_id': contract.id,
                    'amount': values['tax'],
                }),
                
                
                ]
        })
        
        result = payslip.simulate_sheet()
        
        payslip.unlink()
        
        return result
        
    def simulate_sheet(self):
        cr, uid, context = self.env.cr, self.env.uid, self.env.context
        ids = []
        for record in self:
            ids.append(record.id)
        slip_line_pool = self.pool.get('hr.payslip.line')
        sequence_obj = self.pool.get('ir.sequence')
        for payslip in self.browse(ids):
            number = payslip.number or sequence_obj.get(cr, uid, 'salary.slip')
            #delete old payslip lines
            old_slipline_ids = slip_line_pool.search(cr, uid, [('slip_id', '=', payslip.id)], context=context)
#            old_slipline_ids
            if old_slipline_ids:
                slip_line_pool.unlink(cr, uid, old_slipline_ids, context=context)
            if payslip.contract_id:
                #set the list of contract for which the rules have to be applied
                contract_ids = [payslip.contract_id.id]
            else:
                #if we don't give the contract, then the rules to apply should be for all current contracts of the employee
                contract_ids = self.get_contract(cr, uid, payslip.employee_id, payslip.date_from, payslip.date_to, context=context)
            lines = [line for line in self.pool.get('hr.payslip').get_payslip_lines(cr, uid, contract_ids, payslip.id, context=context)]
            #self.write(cr, uid, [payslip.id], {'line_ids': lines, 'number': number,}, context=context)
        
        lines.sort(key=lambda line: line['sequence'])    
        return lines
"""
class smart_salary_simulator_payslip(models.TransientModel):
    _name = "smart_salary_simulator.payslip"
    _description = "Simulated payslip"
    _inherit = 'hr.payslip'
    def simulate_sheet(self):
        cr, uid, context = self.env.cr, self.env.uid, self.env.context
        #ids = []
        #for record in self:
        #    ids.append(record.id)
        slip_line_pool = self.env['hr.payslip.line']
        sequence_obj = self.env['ir.sequence']
        for payslip in self:
            #payslip.number = Reference (t.ex. SLIP/001)
            number = payslip.number or sequence_obj.get('salary.slip')
            #delete old payslip lines
            old_sliplines = slip_line_pool.search([('slip_id', '=', payslip.id)])
#            old_slipline_ids
            for record in old_sliplines:
                slip_line_pool.unlink(cr, uid, [record.id], context=context)
            if payslip.contract_id:
                #set the list of contract for which the rules have to be applied
                contract_ids = [payslip.contract_id.id]
            else:
                #if we don't give the contract, then the rules to apply should be for all current contracts of the employee
                contract_ids = self.get_contract(payslip.employee_id, payslip.date_from, payslip.date_to)
            lines = [(0,0,line) for line in payslip.get_payslip_lines_sim(contract_ids)]
            #self.write(cr, uid, [payslip.id], {'line_ids': lines, 'number': number,}, context=context)
        return lines
        
    @api.one
    def get_payslip_lines_sim(self, contract_ids):
        def _sum_salary_rule_category(localdict, category, amount):
            if category.parent_id:
                localdict = _sum_salary_rule_category(localdict, category.parent_id, amount)
            localdict['categories'].dict[category.code] = category.code in localdict['categories'].dict and localdict['categories'].dict[category.code] + amount or amount
            return localdict
        class BrowsableObject(object):
            def __init__(self, pool, cr, uid, employee_id, dict):
                self.pool = pool
                self.cr = cr
                self.uid = uid
                self.employee_id = employee_id
                self.dict = dict
            def __getattr__(self, attr):
                return attr in self.dict and self.dict.__getitem__(attr) or 0.0
        class InputLine(BrowsableObject):
"""            """a class that will be used into the python code, mainly for usability purposes"""
"""            def sum(self, code, from_date, to_date=None):
                if to_date is None:
                    to_date = datetime.now().strftime('%Y-%m-%d')
                result = 0.0
                self.cr.execute("SELECT sum(amount) as sum\
                            FROM smart_salary_simulator_payslip as hp, hr_payslip_input as pi \
                            WHERE hp.employee_id = %s AND hp.state = 'done' \
                            AND hp.date_from >= %s AND hp.date_to <= %s AND hp.id = pi.payslip_id AND pi.code = %s",
                           (self.employee_id, from_date, to_date, code))
                res = self.cr.fetchone()[0]
                return res or 0.0
        class WorkedDays(BrowsableObject):
"""            """a class that will be used into the python code, mainly for usability purposes"""
"""            def _sum(self, code, from_date, to_date=None):
                if to_date is None:
                    to_date = datetime.now().strftime('%Y-%m-%d')
                result = 0.0
                self.cr.execute("SELECT sum(number_of_days) as number_of_days, sum(number_of_hours) as number_of_hours\
                            FROM smart_salary_simulator_payslip as hp, hr_payslip_worked_days as pi \
                            WHERE hp.employee_id = %s AND hp.state = 'done'\
                            AND hp.date_from >= %s AND hp.date_to <= %s AND hp.id = pi.payslip_id AND pi.code = %s",


Answer:                            (self.employee_id, from_date, to_date, code))