# _*_ coding: utf-8 _*_
# Author: JasonWu( Jaronemo@msn.com)

from odoo import models, fields, api, _
from odoo.fields import Date

CODE_FORMAT = "%s%02d"
# KEY_FORMAT = "%04d%02d%02d"
KEY_FORMAT = "%02d"


class ClassCodeNumber(models.Model):
    _name = 'class.code.number'
    _order = 'key'

    key = fields.Char(string="前置碼")
    course_id = fields.Many2one('jt.course', string='所屬課程')
    next_number = fields.Integer(string="最後號碼", default=0, help="Next number of this sequence")
    year_char = fields.Char(string="Year")
    use_year_range = fields.Boolean(string="每年循環")

    @api.model
    def generate_key_from_date(self, date_str=None, code_name=None):
        if date_str:
            date = Date.from_string(date_str)
            # key = KEY_FORMAT % (date.year, date.month, date.day)
            key_origin = KEY_FORMAT % (date.year)
            # key = code_name + key_origin[2:4]
            key = key_origin[2:4]
            return key

    @api.model
    def next_code_by_key(self, key=None):
        if key:
            class_code_number = self.search([("key", "=", key)])
            if not class_code_number:
                class_code_number = self.create({"key": key})
                class_code_number.ensure_one()

            return class_code_number.next_code()

    @api.multi
    def next_code(self):
        self.ensure_one()
        self.inc_number()
        return self.code()

    @api.multi
    def code(self):
        self.ensure_one()
        return CODE_FORMAT % (self.key, self.next_number)

    @api.multi
    def dec_number(self):
        self.ensure_one()
        self.next_number -= 1
        return True

    @api.multi
    def inc_number(self):
        self.ensure_one()
        self.next_number += 1
        return True

    @api.multi
    def recover_if_biggest(self, code):
        key = code[0:2]
        class_code_number = self.search([("key", "=", key)])
        class_code_number.ensure_one()
        cur_code = class_code_number.code()
        if code == cur_code:
            class_code_number.dec_number()
        return True
