# -*- coding: utf-8 -*-
import sys
import dateparser
from datetime import datetime
from lib.apicalls import *
from lib.utils import *
from lib.htmlgen import *
from lib.graphsgen import *
from lib.langstrings import *
import warnings

warnings.filterwarnings("ignore", category=UserWarning)

msg = getMessages("es")
file_content = ''

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

parser = argparse.ArgumentParser()
parser.add_argument("-x", "--execution", help="Execution Mode", required=False)
parser.add_argument("-t", "--template", help="HTML Template path", required=False)
parser.add_argument("-f", "--facility", help="Facility ID", required=False)
parser.add_argument("-d", "--date", help="Reports date format yyyy-mm", required=False)
parser.add_argument("-c", "--clientname", help="Client Name", required=False)
parser.add_argument("-m", "--clientmail", help="Client Mail", required=False)
parser.add_argument("-r", "--replace", help="Replace old file", required=False)
parser.add_argument("-u", "--force_update", help="Force Report Update (only used on create)", required=False)
parser.add_argument("-w", "--weekly", help="Weekly report", required=False)
args = parser.parse_args()

dirpath = (os.path.dirname(os.path.realpath(__file__)))
os.environ['MPLCONFIGDIR'] = ""+dirpath+"/temp/images/"

def upload_report(pdfFile,data):
  app_id = 1
  api_user = 13510
  api_token = "fc323b1d03569f3be9e598df178017808b8bc9fb"
  month = int(args.date.split("-")[1])
  year = int(args.date.split("-")[0])
  datew = "0"+str(month)+"_"+str(year)
    
  with open(pdfFile, 'rb') as f:
      body = {'user':api_user,'app':app_id,'api_token':api_token,'month_year':datew,'facility_id': data}
      files = {'file': (os.path.basename(pdfFile), f, 'application/pdf')}
      apiCall = requests.post('https://api.gc-track.net/fire_monitoring/app/reports/upload_monthly_report.php', files=files, data=body)
      apiCall.encoding = 'utf-8'
      apiResult = json.loads(apiCall.text)

      if apiResult['data'] != "":
          #deleteTempFiles()
          if str(args.execution) == "create":
            print(str(apiResult['data']))
          else:
            print(f"└[El documento se subio correctamente a la nube]")
      else:
        print(f"└[ERROR]")

def createCompleteReport(rDate,rFacility):
    # facilityId = int(args.facility)
    facilityId = int(rFacility)
    facility = getFacilityInfo(facilityId)
    current_date = datetime.today()
    report_date = ''

    if rDate is not None:
        report_date = datetime.strptime(str(rDate),"%Y-%m") 
    else:
        report_date = current_date    

    weekdays = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"]
    months = [
        "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
        "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
    ]

    formatted_date = f"{months[report_date.month-1]}, {report_date.year}"
    param_date = str(report_date.year)+'-'+str(report_date.month-1)
    param_date_api = str(report_date.year)+'-'+str(report_date.month)
    dirname = (months[report_date.month-1]+'_'+str(report_date.year)).upper()
    dirPathm = dirpath+'/temp/reports/monthly/'+dirname


    if args.weekly != 1:
        createReportDir(dirPathm)
    else:
        print("En construccion")

    try:
        convertClientLogo(facility['logo_png_url'])
    except Exception:
        pass

    try:
        convertCompanyLogo(facility['redbox_vendor_logo_png_url'])
    except Exception:
        pass


    reportData = getMonthlyReportSingle(facilityId,report_date)['facility_data'][0]

    print(facility)

    if args.template is not None:
        file_path = str(args.template)
    else:
        file_path = '/var/www/reporter.gc-track.com/app/res/templates/report_template_monthly.html'    

    with open(file_path, 'r') as file:
        file_content = file.read()

    file_content = file_content.replace("[$facility_name$]",facility['name'])
    
    try:
        file_content = file_content.replace("[$facility_address$]",facility['full_address'])
    except TypeError:
        file_content = file_content.replace("[$facility_address$]","")

    try:
        file_content = file_content.replace("[$postal_address$]",facility['postal_address'])
    except TypeError:
        file_content = file_content.replace("[$postal_address$]","")
        
    
    file_content = file_content.replace("[$DATE_HEADER$]",formatted_date)

    try:
        file_content = file_content.replace("[$facility_data$]",getComponentListHtml(facilityId))
    except TypeError:
        file_content = file_content.replace("[$facility_data$]","")

    try:
        file_content = file_content.replace("[$pressure_graph$]",generatePressureGraphHtml(reportData['pressure_component_id'],str(param_date_api)))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")
        
        
        if str(args.execution) != "create":
            print("├── Generando grafica de presion")
        presureGraphExist = 1
    except TypeError:
        file_content = file_content.replace("[$pressure_graph$]","")
        presureGraphExist = 0

    try:
        file_content = file_content.replace("[$jockey_graph$]",generateJockeyGraphHtml(facility['redbox_id'],str(param_date_api)))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")
        
        if str(args.execution) != "create":
            print("├── Generando grafica de jockey")
        jockeyGraphExist = 1
    except TypeError:
        file_content = file_content.replace("[$jockey_graph$]","")
        jockeyGraphExist = 0

    try:
        file_content = file_content.replace("[$alarm_table$]",generateAlarmTableByMonthHtml(facilityId,str(param_date_api)))
        if str(args.execution) != "create":
            print("├── Generando tabla de panel de alarma")
        alarmTableExist = 1
    except TypeError:
        file_content = file_content.replace("[$alarm_table$]","")
        alarmTableExist = 0

    try:
        file_content = file_content.replace("[$alert_table$]",generateAlertHistorybyMonthHtml(facilityId,str(param_date_api)))
        file_content = file_content.replace("alerts-title-hidden","alerts-title")
        file_content = file_content.replace("alerts-content-hidden","alerts-content")
        

        if str(args.execution) != "create":
            print("├── Generando tabla de alertas en bombas")
        alertTableExist = 1
    except TypeError:
        file_content = file_content.replace("[$alert_table$]","")
        alertTableExist = 0

    try:
        file_content = file_content.replace("[$pump_count$]",getPumpRunCount(facilityId,str(param_date_api)))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")

        if str(args.execution) != "create":
            print("├── Generando conteos de encendidos en bombas")
        pumpCountExist = 1
    except TypeError as error:
        file_content = file_content.replace("[$pump_count$]","")
        pumpCountExist = 0

    try:
        file_content = file_content.replace("[$alarm_count$]",getPumpAlertCount(reportData))
        file_content = file_content.replace("summary-title-hidden","summary-title")
        file_content = file_content.replace("summary-content-hidden","summary-content")

        if str(args.execution) != "create":
            print("├── Generando conteos de alertas en bombas")
        alarmCountExist = 1
    except TypeError:
        file_content = file_content.replace("[$alarm_count$]","")
        alarmCountExist = 0      
    try:
        file_content = file_content.replace("[$detector_count$]",getDetectorCount(reportData))
        file_content = file_content.replace("alerts-title-hidden","alerts-title")
        file_content = file_content.replace("alerts-content-hidden","alerts-content")
        
        
        if str(args.execution) != "create":
            print("├── Generando conteos en panel de alarmas")
        detectorCountExist = 1
    except TypeError:
        file_content = file_content.replace("[$detector_count$]","")
        detectorCountExist = 0     

    try:
        file_content = file_content.replace("[$pump_run_details$]",generatePumpDetails( reportData))
        file_content = file_content.replace("activations-title-hidden","activations-title")
        file_content = file_content.replace("activations-content-hidden","activations-content")

        if str(args.execution) != "create":
            print("├── Generando informacion detallada en bombas")
        pumpRunDetailsExist = 1
    except TypeError:
        file_content = file_content.replace("[$pump_run_details$]","")
        pumpRunDetailsExist = 0      

    try:
        file_content = file_content.replace("[$pump_run_details_mant$]",generatePumpDetailsMant(reportData))
        file_content = file_content.replace("activations-title-hidden","activations-title")
        file_content = file_content.replace("activations-content-hidden","activations-content")

        if str(args.execution) != "create":
            print("├── Generando informacion detallada en bombas en mantenimiento")
        pumpRunDetailsMantExist = 1
    except TypeError:
        file_content = file_content.replace("[$pump_run_details_mant$]","")
        pumpRunDetailsMantExist = 0       


    with open("./temp/result.html", "w") as f:
        f.write(file_content)

    m = months[(report_date.month)-1][:3]
    pdfname = str(facility["shortname"])+"_"+m+str(report_date.year)[-2:]
    pdfname = pdfname.upper()
    
    generatePDF('result.html','reports/monthly/'+dirname+"/"+pdfname+'.pdf')
    return "/var/www/reporter.gc-track.com/app/temp/reports/monthly/"+dirname+"/"+pdfname+'.pdf'

def send_new_mail_monthly(to,name,month,tabledata):
    fromaddr = "support@gc-track.com"
    toaddr = to
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "["+name+"][GC-Track Monitoring System] Reporte mensual de "+month+" 📄"
    body = ''

    table_content = ""

    print(f"┌─[{bcolors.BOLD}"+name+"]")

    for client_data in tabledata:
        if client_data['report_url']:
            print("├── "+client_data['name']+"[🗸]")
            table_content = table_content+'<li><a target="_blank" style="color: #fff;" href="'+client_data['report_url']+'">'+client_data['name']+'</a></li>'
        else:
            print("├── "+client_data['name']+"[𐄂]")
            
    table= table_content
    
    with open(r''+dirpath+'/res/templates/mail_template_monthly.html', 'r') as filea:
        body = filea.read().replace('%table_content',table)
        
    context = ssl.create_default_context()
    msg.attach(MIMEText(body, 'html'))
    #server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
    server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
    server.login(fromaddr, "gldqkbvgpysupvso")
    text = msg.as_string()
    try:
      if not len(table_content) == 0:
          mail_send =  server.sendmail(fromaddr, toaddr, text)
      else:
          raise ValueError("No hay reportes con url, por eso no se envio correo")    
    except smtplib.SMTPRecipientsRefused:
        print("recipient address must contain a domain")
    server.quit()
    server.close()

def send_new_mail_weekly(to, name, month,tabledata):
    fromaddr = "support@gc-track.com"
    toaddr = to
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "[GC-Track Monitoring System] Reporte mensual de "+month+" 📄"
    body = ''
    
    
    table_content = ""
    for client_data in tabledata:
        if client_data['url']:
            print("├── "+client_data['facility']+"[🗸]")
            client_data['url']
            table_content = table_content+'<li><a target="_blank" style="color: #fff;" href="'+client_data['url']+'">'+client_data['facility']+'</a></li>'
        else:
            print("├── "+client_data['facility']+"[𐄂]")
            
    table= table_content
    
    with open(r''+dirpath+'/res/templates/mail_template.html', 'r') as filea:
        body = filea.read().replace('%table_content',table)
        
    context = ssl.create_default_context()
    msg.attach(MIMEText(body, 'html'))
    #server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
    server = smtplib.SMTP_SSL(host='smtp.gmail.com',port=465,context=create_default_context())
    server.login(fromaddr, "gldqkbvgpysupvso")
    text = msg.as_string()
    try:
      if not len(table_content) == 0:
          mail_send =  server.sendmail(fromaddr, toaddr, text)
      else:
          raise ValueError("No hay reportes con url, por eso no se envio correo")    
    except smtplib.SMTPRecipientsRefused:
        print("recipient address must contain a domain")
    server.quit()
    server.close()

if str(args.execution) == "report":
    os.system('clear')
    print("╔════════════════════════════════════════╗")
    print("║      GENERANDO REPORTES MENSUALES      ║")
    print("╚════════════════════════════════════════╝")
    print("")
    month_adjust = 1
    today_a_month_ago = date.today() - relativedelta(months=1)
    v = requests.post('https://api.gc-track.net/fire_monitoring/app/list_prod_facilities.php')
    v.encoding = 'utf-8'
    prodfac = json.loads(v.text)
    prod = prodfac["facilities"]
    
    for p in prod:
            print(f"┌─[{bcolors.BOLD}Compilando "+p["name"]+f" ID: {bcolors.WARNING}"+str(p["id"])+f"{bcolors.ENDC}]")
            upload_report(createCompleteReport(args.date,p["id"]),p["id"])
            print(" ")
            time.sleep(2)

if str(args.execution) == "single":
    os.system('clear')
    print("╔════════════════════════════════════════╗")
    print("║      GENERANDO REPORTE SENCILLO        ║")
    print("╚════════════════════════════════════════╝")
    print("")
    upload_report(createCompleteReport(args.date,args.facility),args.facility)

if str(args.execution) == "create":
    report_date = datetime.strptime(str(args.date),"%Y-%m") 
    date_p = str(report_date.month)+"_"+str(report_date.year)

    #aqui forzara a crear y subir un reporte nuevo
    
    if str(args.force_update) == "1":
        upload_report(createCompleteReport(args.date,args.facility),args.facility)
    else:
        #esta parte buscara su existe un reporte, si existe, regresara tu url
        if find_report(args.facility,date_p)['records'] != '':
            print(find_report(args.facility,date_p)['records'])
        else:
            #En caso de no existir, se creara un reporte nuevo y regresara la url una vez creado
            upload_report(createCompleteReport(args.date,args.facility),args.facility)      

if str(args.execution) == "revision":
    os.system('clear')
    print("╔════════════════════════════════════════════════════╗")
    print("║      GENERANDO DE REVISION REPORTES MENSUALES      ║")
    print("╚════════════════════════════════════════════════════╝")
    print("")
    month_adjust = 1
    today_a_month_ago = date.today() - relativedelta(months=1)
    v = requests.post('https://api.gc-track.net/fire_monitoring/app/list_rev_facilities.php')
    v.encoding = 'utf-8'
    prodfac = json.loads(v.text)
    prod = prodfac["facilities"]
    for p in prod:
            print(f"┌─[{bcolors.BOLD}Compilando "+p["name"]+f" ID: {bcolors.WARNING}"+str(p["id"])+f"{bcolors.ENDC}]")
            upload_report(createCompleteReport(args.date,p["id"]),p["id"])
            time.sleep(5)

if str(args.execution) == "revisionless":
    os.system('clear')
    month_adjust = 1
    today_a_month_ago = date.today() - relativedelta(months=1)
    v = requests.post('https://api.gc-track.net/fire_monitoring/app/list_rev_facilities.php')
    v.encoding = 'utf-8'
    prodfac = json.loads(v.text)
    prod = prodfac["facilities"]
    for p in prod:
            upload_report(createCompleteReport(args.date,p["id"]),p["id"])
            time.sleep(5)

if str(args.execution) == "mail":
    os.system('clear')
    print("╔════════════════════════════════════════╗")
    print("║            ENVIO DE CORREOS            ║")
    print("╚════════════════════════════════════════╝")
    print("")
    mail_clients = []
    app_id = 1
    api_user = 13510
    api_token = "fc323b1d03569f3be9e598df178017808b8bc9fb"
    
    today_a_month_ago = date.today() - relativedelta(months=1)
    if args.date:
        year_str, month_str = args.date.split("-")
        datew = f"{month_str.zfill(2)}_{year_str}"
    else:
        datew = str(today_a_month_ago.month)+"_"+str(today_a_month_ago.year)    
    
    body = {'user':api_user,'app':app_id,'api_token':api_token,'month_year':datew}
    r = requests.post('https://reporter.gc-track.com/api/app/reports/get_usersFacilities_monthly_reporter.php', body)
    r.encoding = 'utf-8'
    response = json.loads(r.text)
    data = response["data"]
    for user in data:
        try:
            user_facilities = user.get('facilities', [])

            send_new_mail_monthly("erick.rodriguez@uabc.edu.mx",user['name'],months[int(args.date.split("-")[1])],user_facilities)
            #send_new_mail_monthly("jorge.parra@gc-track.com",user['name'],months[int(args.date.split("-")[1])],user_facilities)
            print(f"└[ {bcolors.BOLD}{bcolors.OKGREEN}Correo enviado {bcolors.ENDC}]")
            print(" ")
        
        except Exception as e:
            print(f"└[{bcolors.BOLD}{bcolors.FAIL}Falló, razon: "+str(e)+f"{bcolors.ENDC}]")
            print(" ")
            continue
        
        time.sleep(7)
