from odoo import models, api, fields
from datetime import date,datetime
from odoo.exceptions import ValidationError

class Sequence_Generator(models.AbstractModel):
    _name = 'sos_sequence_generator'
    _description = 'Utility for Generating Custom Sequences'

    @api.model
    def generate_sequence(self, model_name, form_name, field_name):
        today = fields.Date.today()
        # Calculate financial year based on April to April cycle
        year_start = today.year if today.month > 3 else today.year - 1
        year_end = year_start + 1
        fy = f"{year_start % 100}-{year_end % 100}"

        month = today.strftime('%m')  # Current month as two-digit string

        # Build the base sequence string to check existing sequences
        base_sequence_prefix = f"SOS/{form_name}/{fy}/{month}/"

        # Query the latest record in the same model with the highest sequence for the current month and fiscal year
        records = self.env[model_name].search(
            [(field_name, 'like', f"{base_sequence_prefix}%")],
            order=f"{field_name} desc",  # Corrected order clause
            limit=1
        )
        if records and records[0][field_name]:
            last_sequence = records[0][field_name]
            # Attempt to split and extract the last number part of the sequence
            try:
                last_number = int(last_sequence.split('/')[-1])
                new_number = last_number + 1
            except ValueError:
                # Fallback if the last sequence isn't properly formatted or can't be converted to an integer
                new_number = 1
        else:
            # No records found for this month and year, start with 001
            new_number = 1

        # Return the complete sequence
        return f"{base_sequence_prefix}{new_number:03d}"

    @staticmethod
    def action_assign_signature(record, image_field_name, user_field_name, no_signature_message=None):
        current_user = record.env.user
        esign = current_user.signature_image

        if esign:
            setattr(record, image_field_name, esign)
            setattr(record, user_field_name, current_user)
        else:
            if no_signature_message:
                return {
                    'type': 'ir.actions.client',
                    'tag': 'display_notification',
                    'params': {
                        'message': no_signature_message,
                        'type': 'danger',
                        'sticky': False
                    }
                }
        return None
    
    @staticmethod
    def calculate_week_number(start_date, end_date, input_date):
        # Check for False values
        if not start_date or not end_date or not input_date:
            raise ValidationError("Without Indent plan you can't do this Opreation")

        start_date_dt = datetime.strptime(str(start_date), '%Y-%m-%d')
        end_date_dt = datetime.strptime(str(end_date), '%Y-%m-%d')
        input_date_dt = datetime.strptime(str(input_date), '%Y-%m-%d')

        if input_date_dt < start_date_dt or input_date_dt > end_date_dt:
            raise ValidationError("Date exceeds the target date range.")
            # Alternatively, you could set a value indicating the date is out of range:
            # return "Date is out of the given range"
        else:
            days_diff = (input_date_dt - start_date_dt).days
            week_number = days_diff // 7 + 1
            return week_number

    @staticmethod
    def send_group_email(env, email_from, email_to, subject, body,group_xml_id):
        group = env.ref(group_xml_id)
        if group:
            users = env['res.users'].search([('groups_id', 'in', [group.id])])
            emails = users.mapped('email')
            # email_to = ','.join(emails)
            mail_values = {
                'subject': subject,
                'body_html': body,
                'email_to': email_to,
                'email_from': email_from,
            }
            mail = env['mail.mail'].sudo().create(mail_values)
            mail.sudo().send()
        else:
            print("No Recepients Found")

    @staticmethod
    def send_mon_min_email(env, email_from, email_to, subject, body,user_type):
        if user_type == "user":
            users = env['res.users'].search([('id', '=', env.user.id)])
            reporting_user = env['res.users'].search([('id', '=', users.reporting_to.id)])
            # email_to = reporting_user.login
        else:
            # email_to = "ramachandran.r@sosaley.in"
            print("test")
        mail_values = {
            'subject': subject,
            'body_html': body,
            'email_to': email_to,
            'email_from': email_from,
        }
        mail = env['mail.mail'].sudo().create(mail_values)
        mail.sudo().send()
