# -*- coding: utf-8 -*-
from weasyprint import HTML, CSS
import time
from datetime import datetime
import subprocess
import os
import json
import pandas as pd
import matplotlib.patches as mpatches
import numpy as np
import pylab as plt
import requests
import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import matplotlib as mpl
import random
import string
import sys
import matplotlib
import re
import urllib.request
import unicodedata
import json
import requests
import re
import locale
import pdfkit
import locale
import argparse
import shutil
import fnmatch
import ssl
import smtplib
import gc
from smtplib import SMTP_SSL, SMTP, SMTPAuthenticationError
from ssl import create_default_context
from email.message import EmailMessage
from datetime import date
from random import randrange
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from urllib.request import urlretrieve
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.fernet import Fernet
from dateutil.relativedelta import relativedelta
import cairosvg
import traceback
import dateparser
from PIL import Image
from lib.apicalls import *
from lib.utils import *
from lib.htmlgen import *
from lib.graphsgen import *
from lib.langstrings import *

class NoPumpsError(Exception):
    pass

def getDetectorInfoHtml(facility):
    data = getDetectorInfo(facility)["detector"]
    return '<div class="detectorInfoTable">  \
    <div class="row">  \
        <div class="cell">id</div>  \
        <div class="cell">"+str(data["id"])+"</div>  \
    </div>  \
    <div class="row">  \
        <div class="cell">detectorstate_id</div>  \
        <div class="cell">"+str(data["detectorstate_id"])+"</div>  \
    </div>  \
    <div class="row">  \
        <div class="cell">label_title</div>  \
        <div class="cell">"+str(data["label_title"])+"</div>  \
    </div> \
    <div class="row">  \
        <div class="cell">label_subtitle</div> \
        <div class="cell">"+str(data["label_subtitle"])+"</div> \
    </div>  \
    <div class="row">  \
        <div class="cell">tag</div>  \
        <div class="cell">"+str(data["tag"])+"</div> \
    </div>  \
    <div class="row">  \
        <div class="cell">type</div>  \
        <div class="cell">"+str(data["type"])+"</div>  \
    </div>  \
    <div class="row">  \
        <div class="cell">serial_number</div>  \
        <div class="cell">"+str(data["serial_number"])+"</div>  \
    </div>  \
    <div class="row"> \
        <div class="cell">technician</div> \
        <div class="cell">"+str(data["technician"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">installation_date</div> \
        <div class="cell">"+str(data["installation_date"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">is_online</div> \
        <div class="cell">"+str(data["is_online"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">is_active</div> \
        <div class="cell">"+str(data["is_active"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">using_battery</div> \
        <div class="cell">"+str(data["using_battery"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">baudrate</div> \
        <div class="cell">"+str(data["baudrate"])+"</div>  \
    </div> \
    <div class="row"> \
        <div class="cell">model</div> \
        <div class="cell">"+str(data["model"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">brand</div> \
        <div class="cell">"+str(data["brand"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">maker</div> \
        <div class="cell">"+str(data["maker"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">tz</div> \
        <div class="cell">"+str(data["tz"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">last_transmission</div> \
        <div class="cell">"+str(data["last_transmission"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">sw_maintenance</div> \
        <div class="cell">"+str(data["sw_maintenance"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">has_securitycontact</div> \
        <div class="cell">"+str(data["has_securitycontact"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">is_battery_enabled</div> \
        <div class="cell">"+str(data["is_battery_enabled"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">is_reset_enabled</div> \
        <div class="cell">"+str(data["is_reset_enabled"])+"</div> \
    </div> \
    <div class="row">\
        <div class="cell">is_sd_enabled</div> \
        <div class="cell">"+str(data["is_sd_enabled"])+"</div>\
    </div> \
    <div class="row"> \
        <div class="cell">is_sd_healthy</div> \
        <div class="cell">"+str(data["is_sd_healthy"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">flag_version</div> \
        <div class="cell">"+str(data["flag_version"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">slave_id</div> \
        <div class="cell">"+str(data["slave_id"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">has_panelmap</div> \
        <div class="cell">"+str(data["has_panelmap"])+"</div> \
    </div> \
    <div class="row">\
        <div class="cell">is_protocol_disconnected</div> \
        <div class="cell">"+str(data["is_protocol_disconnected"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">connection_mode</div> \
        <div class="cell">"+str(data["connection_mode"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">count_bad_transmissions</div> \
        <div class="cell">"+str(data["count_bad_transmissions"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">vendor_id</div> \
        <div class="cell">"+str(data["vendor_id"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">buyer</div> \
        <div class="cell">"+str(data["buyer"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">carrier</div> \
        <div class="cell">"+str(data["carrier"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">icc</div> \
        <div class="cell">"+str(data["icc"])+"</div> \
    </div> \
    <div class="row"> \
        <div class="cell">sim_phonenumber</div> \
        <div class="cell">"+str(data["sim_phonenumber"])+"</div> \
   </div></div>'

def getNewPumpRunCount(stateRecords):
    try:
        data = stateRecords["conteo_arranques_bombas"]
        dataMant = stateRecords["conteo_arranques_bombas_mant"]
    except (KeyError, TypeError):
        return ""

    # Initialize row strings
    pumpNames = ""
    mant_runs = ""
    normal_runs = ""
    total_runs = ""
    
    # --- Bomba Diesel ---
    bd_total = int(data['diesel_activations']) + int(dataMant['diesel_activations'])
    pumpNames += "<th> Bomba Diesel </th>"
    mant_runs += f"<th>{dataMant['diesel_activations']}</th>"
    normal_runs += f"<th>{data['diesel_activations']}</th>"
    total_runs += f"<th>{bd_total}</th>"

    # --- Bomba Electrica ---
    be_total = int(data['electric_activations']) + int(dataMant['electric_activations'])
    pumpNames += "<th> Bomba Electrica </th>"
    mant_runs += f"<th>{dataMant['electric_activations']}</th>"
    normal_runs += f"<th>{data['electric_activations']}</th>"
    total_runs += f"<th>{be_total}</th>"

    # --- Bomba Jockey ---
    bj_total = int(data['jockey_activations']) + int(dataMant['jockey_activations'])
    pumpNames += "<th> Bomba Jockey </th>"
    mant_runs += f"<th>{dataMant['jockey_activations']}</th>"
    normal_runs += f"<th>{data['jockey_activations']}</th>"
    total_runs += f"<th>{bj_total}</th>" 

    if pumpNames:
        content = f'''<table class="count-table">
            <caption>Arranques de motor</caption>
            <thead>
                <tr><th></th>{pumpNames}</tr>
            </thead>
            <tbody>
                <tr><th>En mantenimiento</th>{mant_runs}</tr>
                <tr><th>Fuera de mantenimiento</th>{normal_runs}</tr>
                <tr><th>Total</th>{total_runs}</tr>
            </tbody>
        </table>'''
    else:
        content = ""

    return content

def getNewAlertCount(stateRecords):
    try:
        data = stateRecords["conteo_alertas_generales"]
        dataMant = stateRecords["conteo_alertas_generales_mant"]
    except (KeyError, TypeError):
        return ""

    # Initialize row strings
    pumpNames = ""
    mant_runs = ""
    normal_runs = ""
    total_runs = ""
    
    # --- Bomba Diesel ---
    bd_total = int(data['diesel_activations']) + int(dataMant['diesel_activations'])
    pumpNames += "<th> Bomba Diesel </th>"
    mant_runs += f"<th>{dataMant['diesel_activations']}</th>"
    normal_runs += f"<th>{data['diesel_activations']}</th>"
    total_runs += f"<th>{bd_total}</th>"

    # --- Bomba Electrica ---
    be_total = int(data['electric_activations']) + int(dataMant['electric_activations'])
    pumpNames += "<th> Bomba Electrica </th>"
    mant_runs += f"<th>{dataMant['electric_activations']}</th>"
    normal_runs += f"<th>{data['electric_activations']}</th>"
    total_runs += f"<th>{be_total}</th>"

    # --- Bomba Jockey ---
    bj_total = int(data['jockey_activations']) + int(dataMant['jockey_activations'])
    pumpNames += "<th> Bomba Jockey </th>"
    mant_runs += f"<th>{dataMant['jockey_activations']}</th>"
    normal_runs += f"<th>{data['jockey_activations']}</th>"
    total_runs += f"<th>{bj_total}</th>" 

    if pumpNames:
        content = f'''<table class="count-table">
            <caption>Alertas generales</caption>
            <thead>
                <tr><th></th>{pumpNames}</tr>
            </thead>
            <tbody>
                <tr><th>En mantenimiento</th>{mant_runs}</tr>
                <tr><th>Fuera de mantenimiento</th>{normal_runs}</tr>
                <tr><th>Total</th>{total_runs}</tr>
            </tbody>
        </table>'''
    else:
        content = ""

    return content

def getPumpRunCount(facilityId,month):
    facility_info = getMonthActivations(facilityId,month)['facility_data'][0]
    pumpRun = facility_info.get('pump_running_alerts_count', [])
    jockeyRun = facility_info.get('jockey_pump_activations_count', [])

    pumpNames = ""
    mant_runs = ""
    normal_runs = ""
    total_runs = ""
    
    for pumpn in pumpRun:
        pumpNames = pumpNames + "<th>"+pumpn['pump_name']+"</th>"
        mant_runs = mant_runs + "<th>"+str(pumpn['current_month_count_maintenance'])+"</th>"
        normal_runs = normal_runs + "<th>"+str(pumpn['current_month_count'])+"</th>"
        total_runs = total_runs + "<th>"+str(pumpn['current_month_count_maintenance']+pumpn['current_month_count'])+"</th>"

    for jockey in jockeyRun:
        pumpNames = pumpNames + "<th>Bomba Jockey </th>"
        mant_runs = mant_runs + "<th>"+str(jockey['last30days_maintenance'])+"</th>"
        normal_runs = normal_runs + "<th>"+str(jockey['month_activations'])+"</th>"
        total_runs = total_runs + "<th>"+str(jockey['total'])+"</th>"  

    if pumpNames != "" and mant_runs != "" and normal_runs != "" and total_runs != "":
        content = '<table class="count-table">\
                                    <caption>\
                                        Arranques de motor\
                                    </caption>\
                                    <thead>\
                                        <tr><th></th>\
                                            '+pumpNames+'</tr>\
                                    </thead>\
                                    <tbody>\
                                        <tr>\
                                            <th>En mantenimiento</th>\
                                            '+mant_runs+'\
                                        </tr>\
                                        <tr>\
                                            <th>Fuera de mantenimiento</th>\
                                            '+normal_runs+'\
                                        </tr>\
                                        <tr>\
                                            <th>Total</th>\
                                            '+total_runs+'\
                                        </tr>\
                                    </tbody>\
                                </table>'
    else:
        content = ""

    return content

def getPumpAlertCount(reportData):
    pumpRun = reportData['pump_trouble_alerts_count']

    pumpNames = ""
    mant_runs = ""
    normal_runs = ""
    total_runs = ""
    content = ""

    for pumpn in pumpRun:
        pumpNames = pumpNames + "<th>"+pumpn['pump_name']+"</th>"
        mant_runs = mant_runs + "<th>"+str(pumpn['current_month_count_maintenance'])+"</th>"
        normal_runs = normal_runs + "<th>"+str(pumpn['current_month_count'])+"</th>"
        total_runs = total_runs + "<th>"+str(pumpn['current_month_count']+pumpn['current_month_count_maintenance'])+"</th>"    

    if pumpNames != "" and mant_runs != "" and normal_runs != "" and total_runs != "":
        content = '<table class="count-table">\
                                    <caption>\
                                        Alertas generales\
                                    </caption>\
                                    <thead>\
                                        <tr><th></th>\
                                            '+pumpNames+'</tr>\
                                    </thead>\
                                    <tbody>\
                                        <tr>\
                                            <th>En mantenimiento</th>\
                                            '+mant_runs+'\
                                        </tr>\
                                        <tr>\
                                            <th>Fuera de mantenimiento</th>\
                                            '+normal_runs+'\
                                        </tr>\
                                        <tr>\
                                            <th>Total</th>\
                                            '+total_runs+'\
                                        </tr>\
                                    </tbody>\
                                </table>'
    return content

def getDetectorCount(reportData):
    detector = reportData['alarm_panel_events_counter']
    detectorMan = reportData['alarm_panel_events_mant_counter']
    
    try:
        seg = detector['SEGURIDAD']
        segm = detectorMan['SEGURIDAD']
        segtotal = segm+seg
    except TypeError:
        seg = 0
        segm = 0
        segtotal = 0
   
    content = '<table class="count-table">\
                                    <caption>\
                                        Alertas de panel de alarmas\
                                    </caption>\
                                    <thead>\
                                        <tr>\
                                            <th></th>\
                                            <th>Alarmas de Fuego</th>\
                                            <th>Alarmas de Falla</th>\
                                            <th>Alarmas de Supervisión</th>\
                                            <th>Alarmas de Seguridad</th>\
                                        </tr>\
                                    </thead>\
                                    <tbody>\
                                        <tr>\
                                            <th>En Mantenimiento</th>\
                                            <td>'+str(detectorMan['NORMAL'])+'</td>\
                                            <td>'+str(detectorMan['ALARMA'])+'</td>\
                                            <td>'+str(detectorMan['SUPERVISORIO'])+'</td>\
                                            <td>'+str(segm)+'</td>\
                                        </tr>\
                                        <tr>\
                                            <th>Fuera de Mantenimiento</th>\
                                            <td>'+str(detector['NORMAL'])+'</td>\
                                            <td>'+str(detector['ALARMA'])+'</td>\
                                            <td>'+str(detector['SUPERVISORIO'])+'</td>\
                                            <td>'+str(seg)+'</td>\
                                        </tr>\
                                        <tr>\
                                            <th>Total</th>\
                                            <td>'+str(detector['NORMAL']+detectorMan['NORMAL'])+'</td>\
                                            <td>'+str(detector['ALARMA']+detectorMan['ALARMA'])+'</td>\
                                            <td>'+str(detector['SUPERVISORIO']+detectorMan['SUPERVISORIO'])+'</td>\
                                            <td>'+str(segtotal)+'</td>\
                                        </tr>\
                                    </tbody>\
                                </table>'
    if content != '':
        return content
    else:
        raise TypeError("A descriptive message about the type error.")

def getComponentListHtml(component):
    data = listComponent(component)["component_list"]
    row = '<table class="details><tbody>\
        <tr><thead>\
        <th>id</div>\
        <th>componentclass_id</th>\
        <th>componentstate_id</th>\
        <th>componenttype_id</th>\
        <th>redbox_id</th>\
        <th>facility_id</th>\
        <th>name_es_mx</th>\
        <th>name_en_us</th>\
        <th>description_es_mx</th>\
        <th>description_en_us</th>\
        <th>has_countrecord</th>\
        <th>has_information</th>\
        <th>has_staterecord</th>\
        <th>has_valuerecord</th>\
        <th>graph_type</th>\
        <th>graph_component_id</th>\
        <th>building_id</th>\
        <th>output_states</th>\
        <th>componentstate</th>\
        <th>componenttype</th>\
        <th>output_list</th>\
        </thead></tr>'

    cell_data = ""
    
    for cell in data:
        cell_data = cell_data + '<tr>'
        for cell_text in cell:
            cell_data = cell_data + '<td>'+str(cell[cell_text])+'</td>' 
        cell_data = cell_data + '</tr>'
    
    
    return row+cell_data+'</tbody></table>'

def generateAlarmTableByDateHtml(facilityId,startDate,endDate):
    data = listDetectorMessageByDate(facilityId,startDate,endDate)["detectormessage_list"]
    cell_data = ""
    
    for cell in data:
        cell_data = cell_data +'<tr>'
        cell_data = cell_data +'<td>'+cell["subject_es_mx"]+'</td>'
        cell_data = cell_data +'<td>'+formatDateAlerts(cell["panel_time"])+'</td>'
        cell_data = cell_data +'<tr>'
   
    table = '<table class="alerts-table">\
                                    <caption>\
                                        Notificaciones del panel de alarmas\
                                    </caption>\
                                    <tbody>\
                                        <tr>\
                                            <thead>\
                                                <th class="alerts-description">Descripción</th>\
                                                <th class="alerts-start-date">Fecha</th>\
                                            </thead>\
                                        </tr>\
                                   '+cell_data+'\
                                    </tbody>\
                                </table>'
   
    return table

def generateAlarmTableByMonthHtml(facilityId,date):
    selectedDate = datetime.strptime(str(date),"%Y-%m")
    year = int(selectedDate.year)
    month = int(selectedDate.month)
    startDate = datetime(year,month,1)
    endDate = datetime(year,month+1,1)
    
    try:
        data = listDetectorMessageByDate(facilityId,startDate.strftime("%Y-%m-%d"),endDate.strftime("%Y-%m-%d"))["detectormessage_list"]
    
        cell_data = ""
    
        for cell in data:
            cell_data = cell_data +'<tr>'
            cell_data = cell_data +'<td>'+cell["subject_es_mx"]+'</td>'
            cell_data = cell_data +'<td>'+formatDateAlerts(cell["panel_time"])+'</td>'
            cell_data = cell_data +'<tr>'
   
        table = '<table class="alerts-table">\
                                    <caption>\
                                        Notificaciones del panel de alarmas\
                                    </caption>\
                                    <tbody>\
                                        <tr>\
                                            <thead>\
                                                <th class="alerts-description">Descripción</th>\
                                                <th class="alerts-start-date">Fecha</th>\
                                            </thead>\
                                        </tr>\
                                   '+cell_data+'\
                                    </tbody>\
                                </table>'
    except json.decoder.JSONDecodeError:
        return ""
    
    return table

def generateAlertHistoryHtml(facilityId):
    data = listAlertHistory(facilityId)["redboxmessage_list"]

    cell_data = ""
    
    for cell in data:
        cell_data = cell_data +'<tr>'


        subject = cell["subject_es_mx"]

        if cell["subject_es_mx"] is "Activación":
            subject = "Arranque de Motor de Bomba"
        
        cell_data = cell_data +'<td>'+subject+'</td>'
        
        
        cell_data = cell_data +'<td>'+formatDateAlerts(cell["start_time"])+'</td>'
        cell_data = cell_data +'<td>'+formatDateAlerts(cell["end_time"])+'</td>'
        cell_data = cell_data +'<td>'+cell["active_time"]+'</td>'
        cell_data = cell_data +'<tr>'
   
    table = '<table class="alerts-table">\
                                    <caption>\
                                        Alertas fuera del mantenimiento -'+'d'+'\
                                    </caption>\
                                    <tbody>\
                                        <tr>\
                                            <thead>\
                                                <th class="alerts-description">Descripción</th>\
                                                <th class="alerts-start-date">Inicio</th>\
                                                <th class="alerts-end-date">Restablecimiento</th>\
                                                <th class="alerts-duration">Duración<br>(hh:mm:ss)</th>\
                                            </thead>\
                                        </tr>\
                                   '+cell_data+'\
                                    </tbody>\
                                </table>'
   
    return table

def generateAlertHistorybyMonthHtml(stateRecords):
    content = ''
    tabledata = ''
    details = stateRecords["activaciones_generales"]

    if len(details) < 0:
        content = "<caption>No se encontraron Alertas generales fuera de mantenimiento</caption>"
        return content
    
    
    for pumprun in details:
        event = pumprun.get('output_name', 'N/A')
        device = pumprun.get('component_type', 'N/A')
        start = pumprun.get('start_time', 'N/A')
        end = pumprun.get('end_time', 'N/A')
        duration = pumprun.get('active_time', 'N/A')
        tabledata += f'<tr><td>{event}</td><td>{device}</td><td>{formatDateAlerts(start)}</td><td>{formatDateAlerts(end)}</td><td>{duration}</td></tr>'

    if tabledata:
        content += f'''
        <table class="activations-table">
            <caption>Alertas generales fuera de mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-duration">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
                {tabledata}
            </tbody>
        </table>'''
            
    if content != '':
        return content
    else:
        raise TypeError("A descriptive message about the type error.")

def generateAlertHistorybyMonthHtmlMant(stateRecords):
    content = ''
    tabledata = ''
    details = stateRecords["activaciones_generales_mant"]

    if len(details) < 0:
        content = "<caption>No se encontraron alertas generales en mantenimiento</caption>"
        return content
    
    for pumprun in details:
        event = pumprun.get('output_name', 'N/A')
        device = pumprun.get('component_type', 'N/A')
        start = pumprun.get('start_time', 'N/A')
        end = pumprun.get('end_time', 'N/A')
        duration = pumprun.get('active_time', 'N/A')
        tabledata += f'<tr><td>{event}</td><td>{device}</td><td>{formatDateAlerts(start)}</td><td>{formatDateAlerts(end)}</td><td>{duration}</td></tr>'

    if tabledata:
        content += f'''
        <table class="activations-table">
            <caption>Alertas generales en mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-duration">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
                {tabledata}
            </tbody>
        </table>'''
            
    if content != '':
        return content
    else:
        raise TypeError("A descriptive message about the type error.")

def generateAlertHistoryByDateHtml(facilityId,startDate,endDate):
    try:
      data = listAlertHistoryByDate(facilityId,startDate,endDate)["redboxmessage_list"]
        
      cell_data = ""
    
      for cell in data:
          cell_data = cell_data +'<tr>'
          cell_data = cell_data +'<td>'+cell["subject_es_mx"]+'</td>'
          cell_data = cell_data +'<td>'+formatDateAlerts(cell["start_time"])+'</td>'
          cell_data = cell_data +'<td>'+formatDateAlerts(cell["end_time"])+'</td>'
          cell_data = cell_data +'<td>'+cell["active_time"]+'</td>'
          cell_data = cell_data +'<tr>'
   
      table = '<table class="alerts-table">\
                                    <caption>\
                                        Alertas fuera del mantenimiento -'+'d'+'\
                                    </caption>\
                                    <tbody>\
                                        <tr>\
                                            <thead>\
                                                <th class="alerts-description">Descripción</th>\
                                                <th class="alerts-start-date">Inicio</th>\
                                                <th class="alerts-end-date">Restablecimiento</th>\
                                                <th class="alerts-duration">Duración<br>(hh:mm:ss)</th>\
                                            </thead>\
                                        </tr>\
                                   '+cell_data+'\
                                    </tbody>\
                                </table>'
    except Exception:
        return ""

    return table

def generatePressureGraphHtml(componentId,month):
    path = generatePressureGraph(componentId,month)
    if path != "":
        return '<div class="graph"><h3 class="graph-title">Comportamiento de presión de sistema</h3><img src="./images/graph_pressure.svg" /></div>'
    else:
        raise TypeError("A descriptive message about the type error.")
    
def generateJockeyGraphHtml(componentId,month):
    path = generateJockeyGraph(componentId,month)
    if path != "":
        return '<div class="graph"><h3 class="graph-title">Conteo de arranques de bomba jockey</h3><img src="./images/graph_jockey.svg" /></div>'
    else:
        raise TypeError("A descriptive message about the type error.")

def generatePumpDetails(stateRecords):
    content = ''
    tabledata = ''
    details = stateRecords["arranques_bombas"]

    if len(details) < 0:
        raise NoPumpsError("A descriptive message about the type error.")
  
    for pumprun in details:
        event = "Arranque de Motor de Bomba"
        device = pumprun.get('component_type', 'N/A')
        start = pumprun.get('start_time', 'N/A')
        end = pumprun.get('end_time', 'N/A')
        duration = pumprun.get('active_time', 'N/A')
        tabledata += f'<tr><td>{event}</td><td>{device}</td><td>{formatDateAlerts(start)}</td><td>{formatDateAlerts(end)}</td><td>{duration}</td></tr>'

    if tabledata:
        content += f'''
        <table class="activations-table">
            <caption>Arranques fuera de mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-duration">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
                {tabledata}
            </tbody>
        </table>'''
            
    if content != '':
        return content
    else:
        raise TypeError("A descriptive message about the type error.")

def generatePumpDetailsMant(stateRecords):
    content = ''
    tabledata = ''
    details = stateRecords["arranques_bombas_mant"]

    if len(details) < 0:
        content = "<caption>No se encontraron arranques en mantenimiento</caption>"
        return content 
    
    for pumprun in details:
        event = "Arranque de Motor de Bomba"
        device = pumprun.get('component_type', 'N/A')
        start = pumprun.get('start_time', 'N/A')
        end = pumprun.get('end_time', 'N/A')
        duration = pumprun.get('active_time', 'N/A')
        tabledata += f'<tr><td>{event}</td><td>{device}</td><td>{formatDateAlerts(start)}</td><td>{formatDateAlerts(end)}</td><td>{duration}</td></tr>'

    if tabledata:
        content += f'''
        <table class="activations-table">
            <caption>Arranques en mantenimiento</caption>
            <thead>
                <tr>
                    <th class="activations-description">Descripción</th>
                    <th class="activations-duration">Equipo</th>
                    <th class="activations-start-date">Inicio</th>
                    <th class="activations-end-date">Restablecimiento</th>
                    <th class="activations-duration">Duración<br>(hh:mm:ss)</th>
                </tr>
            </thead>
            <tbody>
                {tabledata}
            </tbody>
        </table>'''
            
    if content != '':
        return content
    else:
        raise TypeError("A descriptive message about the type error.")