# -*- coding: utf-8 -*-
from weasyprint import HTML, CSS
import calendar
from datetime import datetime
import time
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 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 *
from lib.langstrings import *

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

lang = "es"
months = getMonths(lang)
msg = getMessages(lang)

def get_empty_month_data(datemonth):
    parts = datemonth.split("-")
    year = int(parts[0])
    month = int(parts[1])

    num_days = calendar.monthrange(year, month)[1]
    entries = [{'x': int(datetime(year, month, day).timestamp()), 'y': 0} for day in range(1, num_days + 1)]
    
    return [
        {
            'name_en_us': 'Minimum Pressure',
            'name_es_mx': 'Presión Mínima',
            'entry': entries,
            'style': 'solid',
            'color_palette': '#829FD9'
        },
        {
            'name_en_us': 'Maximum Pressure',
            'name_es_mx': 'Presión Máxima',
            'entry': entries,
            'style': 'solid',
            'color_palette': '#0029FA'
        }
    ]

def generatePressureGraphLog(componentId,month):

    path = ""
    filename = ""
    graphData = getPressureGraphData(componentId,month)

    print(graphData)

    try:
        if graphData:
            filename = "graph_pressure.svg"
            ax = plt.gca()
            path = r""+dirpath+"/temp/images/"+filename
            
            try:
                for l in graphData["line"]:
                    try:
                        plt.axhline(l["value"], linewidth=.75, color=str(l["color_palette"]), linestyle="dashed", label=l["name_es_mx"]+" "+str(l["value"])+" PSI")
                    except TypeError as err:
                        print(traceback.format_exc())
                        pass
            except KeyError:
                print(traceback.format_exc())
                filename=""
                pass

            try:
                for g in graphData["graph"]:
                    df = pd.DataFrame(g["entry"])
                    df["date"] = df["x"].map(lambda val: dt.datetime.fromtimestamp(val).strftime("%-d"))
                    if g["style"] == "bar":
                        df.plot(kind="bar", x="x", y="y",color=str(g["color_pallete"]),ax=ax,label=g["name_es_mx"])
                        si = 0
                        for y in df["y"]:
                            ax.text(si-.15, y+.13, str(y), fontsize=6)
                            si = si + 1
                    if g["style"] == "solid":
                        if str(g["name_es_mx"]) in "Mínimo":
                            df.plot(kind="line", x="date", y="y", linewidth=1, marker=".", markersize=1, color=str(g["color_palette"]), ax=ax, label=g["name_es_mx"])
                            si = 0
                            for y in df["y"]:
                                ax.text(si-.20, y-1.8, str(y), fontsize=4)
                                si = si + 1
                    
                        else:
                            df.plot(kind="line", x="date", y="y", linewidth=1, marker=".", markersize=1, color=str(g["color_palette"]), ax=ax, label=g["name_es_mx"])
                            si = 0
                            for y in df["y"]:
                                ax.text(si-.20, y+1.8, str(y), fontsize=4)
                                si = si + 1
            
            except Exception as err:
                print(traceback.format_exc())
                pass
            
    
            plt.xticks(fontsize=8)

            try:
                ax.set_xticks(df.index)
                ax.set_xticklabels(df.date,rotation=0)
            
            except Exception as err:
                print(traceback.format_exc())
                filename=""
                pass
            

        else:
            jmonth = date.month-1
            jyear = date.year

        try:
            plt.rcParams["font.serif"] = "cmr10"
            plt.rcParams["axes.unicode_minus"]=False 
            plt.grid(which="major", color="#999999",linestyle="-", alpha=0.2)
            plt.ylabel("PSI", fontsize=10)
            
            plt.xlabel(msg["day_of_the_month"]+" "+months[int(month.split("-")[1])], fontsize=10)
              
            handles, labels = ax.get_legend_handles_labels()
            box = ax.get_position()
            ax.set_position([box.x0, box.y0 + box.height * 0.2,box.width, box.height * 0.9])
            ax.legend(fontsize=8,loc="upper center", bbox_to_anchor=(0.15, -0.1),fancybox=True, shadow=True, ncol=1)
            plt.rcParams["figure.figsize"] = [16, 9]
            
            try:
                ax.set_ylim(0, int(graphData["highest_value"])+10)
            except Exception as err:
                ax.set_ylim(0,200)
            
            plt.savefig(path, format="svg",orientation="landscape", bbox_inches="tight")
            plt.cla()
            plt.clf()

        except Exception as err:
            print(traceback.format_exc())
            pass
    
    except Exception as err:
        print(traceback.format_exc())
        filename=""
        pass

    return filename

def generatePressureGraph(componentId,month):

    path = ""
    filename = ""
    graphData = getPressureGraphData(componentId,month)

    try:
        if graphData:
            filename = "graph_pressure.svg"
            ax = plt.gca()
            path = r""+dirpath+"/temp/images/"+filename
            
            try:
                for l in graphData["line"]:
                    try:
                        plt.axhline(l["value"], linewidth=.75, color=str(l["color_palette"]), linestyle="dashed", label=l["name_es_mx"]+" "+str(l["value"])+" PSI")
                    except TypeError as err:
                        #print(traceback.format_exc())
                        pass
            except KeyError:
                #print(traceback.format_exc())
                #filename=""
                pass

            if graphData["graph"] != [None]:
                graphentries = graphData["graph"]
            else:
                graphentries = get_empty_month_data(month)

            try:
                for g in graphentries:
                    df = pd.DataFrame(g["entry"])
                    df["date"] = df["x"].map(lambda val: dt.datetime.fromtimestamp(val).strftime("%-d"))
                    if g["style"] == "bar":
                        df.plot(kind="bar", x="x", y="y",color=str(g["color_pallete"]),ax=ax,label=g["name_es_mx"])
                        si = 0
                        for y in df["y"]:
                            ax.text(si-.15, y+.13, str(y), fontsize=6)
                            si = si + 1
                    if g["style"] == "solid":
                        if str(g["name_es_mx"]) in "Mínimo":
                            df.plot(kind="line", x="date", y="y", linewidth=1, marker=".", markersize=1, color=str(g["color_palette"]), ax=ax, label=g["name_es_mx"])
                            si = 0
                            for y in df["y"]:
                                ax.text(si-.20, y-1.8, str(y), fontsize=4)
                                si = si + 1
                        else:
                            df.plot(kind="line", x="date", y="y", linewidth=1, marker=".", markersize=1, color=str(g["color_palette"]), ax=ax, label=g["name_es_mx"])
                            si = 0
                            for y in df["y"]:
                                ax.text(si-.20, y+1.8, str(y), fontsize=4)
                                si = si + 1
            except Exception as err:
                print(traceback.format_exc())
                return ""

            plt.xticks(fontsize=8)

            try:
                ax.set_xticks(df.index)
                ax.set_xticklabels(df.date,rotation=0)
            
            except Exception as err:
                print(traceback.format_exc())
                #filename=""
                pass
            
        else:
            jmonth = date.month-1
            jyear = date.year

        try:
            plt.rcParams["font.serif"] = "cmr10"
            plt.rcParams["axes.unicode_minus"]=False 
            plt.grid(which="major", color="#999999",linestyle="-", alpha=0.2)
            plt.ylabel("PSI", fontsize=10)
            
            plt.xlabel(msg["day_of_the_month"]+" "+months[int(month.split("-")[1])], fontsize=10)
              
            handles, labels = ax.get_legend_handles_labels()
            box = ax.get_position()
            ax.set_position([box.x0, box.y0 + box.height * 0.2,box.width, box.height * 0.9])
            ax.legend(fontsize=8,loc="upper center", bbox_to_anchor=(0.15, -0.1),fancybox=True, shadow=True, ncol=1)
            plt.rcParams["figure.figsize"] = [16, 9]
            
            try:
                ax.set_ylim(0, int(graphData["highest_value"])+10)
            except Exception as err:
                ax.set_ylim(0,300)
            
            plt.savefig(path, format="svg",orientation="landscape", bbox_inches="tight")
            plt.cla()
            plt.clf()

        except Exception as err:
            #print(traceback.format_exc())
            pass
    
    except Exception as err:
        #print(traceback.format_exc())
        filename=""
        pass

    return filename

def generateJockeyGraph(redboxId,dateString):
    path = ""
    filename = ""
    datar = getJockeyGraphData(redboxId,dateString)   
    jockeyAct = datar["data"]

    try:

        try:
            filename = "graph_jockey.svg"
            path = r""+dirpath+"/temp/images/"+filename
            ax = plt.gca()
            df = pd.DataFrame(jockeyAct[0]["jockey_activations"])
            ax.set_ylim(bottom=0, top=(df["activations"].max()+5))
            
            try:
                
                df["x"] = df["date"].map(lambda val: dt.datetime.strptime(val, "%Y-%m-%d").strftime("%-d"))
                df.plot(kind="bar", x="x", y="activations", color=str("#0096c7"), ax=ax, label=str(msg["activation"]))
                si = 0
                for y in df["activations"]:
                    ax.text(si-.35, y+.50, str(y), fontsize=6)
                    si = si + 1
            except KeyError:
                pass
            plt.xticks(fontsize=5)
            plt.grid(which="major", color="#999999",linestyle="-", alpha=0.2)
            plt.ylabel(str(msg["activation"]), fontsize=10)
            plt.xlabel(str(msg["day_of_the_month"]+months[int(dateString.split("-")[1])]), fontsize=10)
            plt.legend(loc="best", prop={"size": 6})
            plt.rcParams["figure.figsize"] = [16, 9]
            plt.savefig(path, format="svg",orientation="landscape", bbox_inches="tight")
            plt.cla()
            plt.clf()

        except KeyError as err:
            print("KEYERROR")

        except FileNotFoundError as err:
            path = null
    except IndexError:
        pass
    return filename