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

class Battery_Installation_Requirement(models.Model):
    _name = 'sos_proposal_customer_requirement'
    _description = 'Battery Installation Details'
    _rec_name="proposal_id"
    proposal_id = fields.Char(string="Proposal ID", readonly= True, required= True, default=lambda self: self._generate_id())
    customer_name = fields.Char(string="Customer Name", required=True)
    location = fields.Char(string="Delivery Location")
    direction = fields.Selection(
            [
               ('North', 'North'), 
                ('West', 'West'), 
                ('East', 'East'),  
                ('South', 'South')                
            ],
            string="Direction",default="South")
    installation_location = fields.Char(string="Installation Location")
    type_of_source = fields.Selection(
    selection=[
        ('inverter', 'Inverter'),
        ('ups', 'UPS'),
        ('pcs', 'PCS'),
        ('charger', 'Charger')
    ],
    string="Type of Source"
)
    number_of_batteries = fields.Integer(string="Number of Batteries",compute="_compute_overall_batteries")
    number_of_strings = fields.Integer(string="Number of Strings")
    number_of_ups = fields.Integer(string="Number of UPS")
    ups_rating_kva = fields.Integer(string="UPS Rating (KVA)")
    no_of_electrical_panel = fields.Integer(string="No of Electrical Panel")
    battery_capacity_ah = fields.Integer(string="Battery Capacity (AH)")
    specific_requirements = fields.Html(string="Specific Requirements")
    products = fields.Selection(
            [
               ('BHMS 1.2V', 'BHMS 1.2V'), 
                ('BHMS 2V', 'BHMS 2V'), 
                ('BHMS 12V', 'BHMS 12V'),  
                ('BHMS 48V', 'BHMS 48V'),
                ('BMS-HV', 'BMS-HV'),
                ('BMS-LV 100A', 'BMS-LV 100A'), 
                ('BMS-LV 40A', 'BMS-LV 40A'), 
                ('SBMS 55A', 'SBMS 55A'),              
                ('MC 250W', 'MC 250W'),                                
                ('HeartTarang', 'HeartTarang')                 
            ],
            string="Products",default="BHMS 12V")
    cloud_subscription = fields.Selection([
        ('yes', 'Yes'),
        ('no', 'No')
    ], string="Cloud Subscription", default='yes')
    internet_connectivity = fields.Selection([
        ('yes', 'Yes'),
        ('no', 'No')
    ], string="Internet Connectivity", default='yes')
    duct_type = fields.Selection([
        ('pvc', 'PVC'),
        ('metal', 'Metal')
    ], string="Duct Type", default='metal')
    communication_type = fields.Selection([
        ('wired', 'Wired'),
        ('wireless', 'Wireless')
    ], string="Communication Type", default='wired')

    requirement_submitted_by_name = fields.Many2one('res.users', string='Requirement Submitted By')
    requirement_submitted_by_image = fields.Image(related="requirement_submitted_by_name.signature_image",readonly=True)
    requirement_submitted_by_approved_on = fields.Datetime(string="Submitted On")
    ups_line_ids = fields.One2many('dynamic_ups_line', 'parent_id', string="UPS Details")
    warranty=fields.Char(string="Warranty (In Months)")
    # Fields for 1.2V
    master_type = fields.Selection([
        ('AC 110V', 'AC 110V'),
        ('AC 220V', 'AC 220V'),
        ('DC 110V', 'DC 110V'),
        ('DC 220V', 'DC 220V')
    ], string="Master Type", default='AC 110V')
    slave_type = fields.Selection([
        ('15S Individual Slave', '15S Individual Slave'),
        ('90S Electrical Panel', '90S Electrical Panel')
    ], string="Slave Type", default='15S Individual Slave')
    ntc = fields.Selection([
        ('Individual', 'Individual'),
        ('Pilot', 'Pilot')
    ], string="NTC Req", default='Individual')
    boq_submitted_by_name = fields.Many2one(
        'res.users', 
        string="BOQ Submitted By", 
        compute="_compute_boq_submitted_by", 
        store=False
    )
    acc_approved_by_name = fields.Many2one(
        'res.users', 
        string="Accounts Costing By", 
        compute="_compute_acc_costing_submitted_by", 
        store=False
    )
    @api.onchange('installation_location')
    def _onchange_location_set_direction(self):
        if not self.installation_location:
            return

        loc = self.installation_location.strip().lower()

        north_states = [
        'delhi', 'punjab', 'haryana', 'uttar pradesh', 'up',
        'uttarakhand', 'himachal pradesh', 'chandigarh',
        'jammu', 'ladakh'
        ]
        west_states = [
            'gujarat', 'maharashtra', 'goa', 'rajasthan',
            'daman', 'diu', 'dadra', 'nagar haveli'
        ]
        east_states = [
            'bihar', 'jharkhand', 'west bengal', 'odisha', 'orissa', 'sikkim',
            'assam', 'arunachal', 'meghalaya', 'manipur', 'mizoram', 'nagaland', 'tripura'
        ]
        south_states = [
            'tamil nadu', 'tamilnadu', 'kerala', 'karnataka',
            'andhra pradesh', 'telangana', 'puducherry', 'lakshadweep'
        ]

        # Match by checking if any state name is a substring of location
        if any(state in loc for state in north_states):
            self.direction = 'North'
        elif any(state in loc for state in west_states):
            self.direction = 'West'
        elif any(state in loc for state in east_states):
            self.direction = 'East'
        elif any(state in loc for state in south_states):
            self.direction = 'South'
        else:
            self.direction = False 
    
    def _compute_acc_costing_submitted_by(self):
        for rec in self:
            boq = self.env['sos_proposal_boq'].search([('proposal_id', '=', rec.proposal_id)], limit=1)
            rec.acc_approved_by_name = boq.acc_approved_by_name if boq else False
    def _compute_boq_submitted_by(self):
        for rec in self:
            boq = self.env['sos_proposal_boq'].search([('proposal_id', '=', rec.proposal_id)], limit=1)
            rec.boq_submitted_by_name = boq.boq_submitted_by_name if boq else False
    @api.depends('ups_line_ids.total_batteries')
    def _compute_overall_batteries(self):
        for record in self:
            record.number_of_batteries = sum(line.total_batteries for line in record.ups_line_ids)
    @api.onchange('number_of_ups')
    def _onchange_number_of_ups(self):
        if self.number_of_ups is not None:
            self.no_of_electrical_panel = self.number_of_ups
            if self.number_of_ups > 15:
                raise ValidationError("Number of UPS cannot be more than 15.")

            lines = [(5, 0, 0)]  # clear all
            for i in range(self.number_of_ups):
                lines.append((0, 0, {
                    'name': f'UPS {i + 1}',
                    'ups_index': i + 1
                }))
            self.ups_line_ids = lines

    def action_sales_esign_btn(self):
        body_html = f"""
        <p>Below <b>Proposal</b> is waiting for your BOQ Updation</p>
        """
        sequence_util = self.env['sos_common_scripts']
        sequence_util.send_group_email(self.env,'sos_proposal_customer_requirement',self.id,"deenalaura.m@sosaley.in","Proposal System - Customer Requirements",body_html,'sos_inventory.sos_ce_head')
        return sequence_util.action_assign_signature(
        self, 
        'requirement_submitted_by_name',
        'requirement_submitted_by_approved_on'
    )
    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_proposal_customer_requirement','PROPOSAL', 'proposal_id')


class UPSLine(models.Model):
    _name = 'dynamic_ups_line'
    _description = 'UPS String Line'

    parent_id = fields.Many2one('sos_proposal_customer_requirement', string="Parent")
    name = fields.Char(string="Name")
    ups_index = fields.Integer(string="UPS Index",store=True)
    battery_capacity_ah = fields.Integer(string="Battery Capacity (AH)")
    ups_capacity_kva = fields.Integer(string="UPS Capacity (KVA)")
    number_of_strings_per_battery = fields.Integer(
    string="Number of Strings"
)
    number_of_batteries = fields.Integer(string="Number of Batteries")
    total_batteries =  fields.Integer(string="Total Batteries",compute="_compute_total_batteries")
    @api.depends('number_of_strings_per_battery', 'number_of_batteries')
    def _compute_total_batteries(self):
        for rec in self:
            strings = int(rec.number_of_strings_per_battery) if rec.number_of_strings_per_battery else 0
            rec.total_batteries = strings * rec.number_of_batteries
    