# -*- coding: utf-8 -*-
from weasyprint import HTML, CSS
import time
import subprocess
from datetime import datetime
from datetime import datetime, timedelta
from email.message import EmailMessage
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 datetime as dt
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 *

dirpath = '/var/www/reporter.gc-track.com/app/'
os.environ['MPLCONFIGDIR'] = ""+dirpath+"/temp/images/"

weekdays = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"]
months = [
    "enero", "febrero", "marzo", "abril", "mayo", "junio",
    "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"
]

def find_replace(string, dictionary):
    for item in sorted(dictionary.keys(), key=len, reverse=True):
        string = re.sub(item, dictionary[item], string)
    return string

def randomString(stringLength=10):
    letters = string.ascii_lowercase
    return "".join(random.choice(letters) for i in range(stringLength))

def deleteTempFiles():
    folder = ""+dirpath+"/temp/images/"
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            if str(args.execution) != "create" and str(args.execution) != "revisionless":
                print("Failed to delete %s. Reason: %s" % (file_path, e))

    directory = ""+dirpath+"/temp/"
    files_in_directory = os.listdir(directory)
    filtered_files = [file for file in files_in_directory if file.endswith(".html")]
    for file in filtered_files:
        path_to_file = os.path.join(directory, file)
        os.remove(path_to_file)

def getJockeyZeroes(data):
    jockeyCount = 0
    try:
        df = pd.DataFrame(data["jockey_activations"])
        for y in df["activations"]:
            if y == 0:
                jockeyCount=jockeyCount+1
        return jockeyCount        
    except KeyError:
        return jockeyCount

def convertClientLogo(logoUrl):
    try:
        urlretrieve(logoUrl,dirpath+"/temp/images/logo_client_temp.png")
        converted_png = dirpath+"/temp/images/logo_client_temp.png"
        image = Image.open(converted_png)
        image.thumbnail((150, 75))
        image.save(dirpath+"/temp/images/logo_temp_client_png_re.png")
    except Exception:
        return ""
    return "temp/images/logo_temp_client_png_re.png"

def convertCompanyLogo(logoUrl):
    try:
        urlretrieve(logoUrl,dirpath+"/temp/images/logo_company_temp.png")
        converted_png = dirpath+"/temp/images/logo_company_temp.png"
        image = Image.open(converted_png)
        image.thumbnail((150, 75))
        image.save(dirpath+"/temp/images/logo_temp_company_png_re.png")
    except Exception:
        return ""
    return "temp/images/logo_temp_company_png_re.png"

def find_file(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result = name
                break
    return result

def formatDateAlerts(timestamp):
        start_time = dateparser.parse(timestamp)
        
        try:
            formatted_date = (
            f"{weekdays[start_time.weekday()]}, {start_time.day} de {months[start_time.month - 1]} del {start_time.year}, "
            f"a las {start_time.strftime('%H:%M:%S')}"
            )
        except AttributeError:
            formatted_date = "-"
        return formatted_date

def generatePDF(filename,pdfname):
    file = r""+dirpath+"/temp/"+filename
    output_path = os.path.join(dirpath, "temp", pdfname)
    HTML(file).write_pdf(
    output_path, 
    pdf_variant="pdf/a-3u"
    )

def createReportDir(DirName):
    try:
        os.makedirs(DirName)
    except FileExistsError:
        pass
    except Exception as e:
        print(f"ERROR EN CREACION DE DIRECTORIO: {e}")

def getStateRecords(redboxId, date):
    selectedDate = datetime.strptime(str(date), "%Y-%m")
    startDate = datetime(selectedDate.year, selectedDate.month, 1)
    if selectedDate.month == 12:
        next_month_start = datetime(selectedDate.year + 1, 1, 1)
    else:
        next_month_start = datetime(selectedDate.year, selectedDate.month + 1, 1)
    
    endDate = next_month_start - timedelta(seconds=1)
    
    return getNewPumpInfo(redboxId, startDate, endDate)["records"]      