from qgis.PyQt.QtWidgets import QMainWindow
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pytz
matplotlib.use('Qt5Agg')

import numpy as np
import pandas as pd
import statistics
from math import ceil

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure

class MplCanvas(FigureCanvasQTAgg):
    def __init__(self, parent, width, height, dpi):
        plt.rcParams["font.family"] = "Marianne"
        self.fig = Figure(figsize=(width/dpi, height/dpi), dpi=dpi)
        self.axes = self.fig.add_subplot(111)
        super(MplCanvas, self).__init__(self.fig)

    def saveImf(self, fileName) : self.fig.savefig(fileName, bbox_inches='tight')

class lineGraph(QMainWindow):
    def __init__(self, ticks_dates, datas, title, typeInfos, tz, fileName, minY, maxY, *args, **kwargs):
        super(lineGraph, self).__init__(*args, **kwargs)
        sc = MplCanvas(self, width=2000, height=1000, dpi=196) #3000 - 1500
        self.ticks_dates = ticks_dates
        self.data = datas
        self.fileName = fileName
        self.title = title
        self.typeInfos = typeInfos
        self.timezone = tz
        self.minY, self.maxY = minY, maxY
        self.lblOriginalData = 'Observations brutes'

        sc.axes.plot(self.ticks_dates , self.data, linestyle="dotted",  label=self.lblOriginalData, marker="o", markersize=1.0, color='dodgerblue')

        formatter = mdates.DateFormatter("%d/%m/%Y %Hh%Mm")
        formatter.set_tzinfo(pytz.timezone(self.timezone)) 
        sc.axes.xaxis.set_major_formatter(formatter)
        
        for label in (sc.axes.get_xticklabels() + sc.axes.get_yticklabels()):
            label.set_fontname('Arial')
            label.set_fontsize(7)          

        sc.axes.set(xlabel='Période', ylabel='Hauteurs (m)', title=self.title) if self.typeInfos == "H" else sc.axes.set(xlabel='Période', ylabel='Débit m3/s', title=self.title)
        sc.fig.autofmt_xdate()
        sc.axes.xaxis.set_tick_params(rotation=30, labelsize=10)
        sc.axes.set_ylim([self.minY*0.75, self.maxY*1.25])
        sc.axes.grid(axis='x', linestyle='dotted', alpha=0.7, zorder=0)
        sc.axes.grid(axis='y', linestyle='dotted', alpha=0.7, zorder=0)
        sc.axes.grid(True)
        sc.axes.legend(fontsize=5, loc=1) 
        
        self.setCentralWidget(sc)
        sc.saveImf(self.fileName)


