from imgui_bundle import (
    implot,
    imgui,
    immapp,
    immvision,
    imgui_toggle,
    ImVec4,
    ImVec2
)

from PIL import Image
import io
import numpy as np
from pdf2image import convert_from_path
from pathlib import Path
from playwright.sync_api import sync_playwright as pw


immvision.use_rgb_color_order()

def plot_bar_line_percentage(data: np.array, labels: list, avg: float) -> None:
    if not data.size > 0:
        imgui.text("No Data available")
        return 

    name = hash(avg)

    if avg.is_integer():
        avg = int(avg)
    avg = np.ones(len(data)) * avg

    w, h = imgui.get_window_size()
    implot.push_colormap(implot.Colormap_.hot.value)
    if implot.begin_plot(f"Performance##{name}", ImVec2(-1, h*0.8), implot.Flags_.no_mouse_text.value | implot.Flags_.no_inputs.value):
        implot.setup_axes("Lectures", "Percentage")
        implot.setup_axes_limits(-1, len(data), 0, 110)
        implot.push_style_var(implot.StyleVar_.fill_alpha.value, 0.6)
        implot.push_style_var(implot.StyleVar_.line_weight.value, 3)
        implot.setup_axis_ticks(implot.ImAxis_.x1.value, 0, len(labels), len(labels), [" " for _ in labels], False)
        implot.plot_bars("Submissions", data)
        implot.plot_line("Average", avg)
        
        implot.push_style_color(implot.Col_.inlay_text, ImVec4(190,190,40,255)/255)
        for x_pos, label in enumerate(labels):
            y_pos = 50
            implot.plot_text(label, x_pos, y_pos//2, ImVec2(0,0), implot.TextFlags_.vertical.value)
        implot.pop_style_color()

        implot.pop_style_var()
        implot.end_plot()

def plot_pie(data: np.array, labels: list, title: str = "Group Performance") -> None:
    if not data.size > 0:
        imgui.text("No Data available")
        return
    
    name = hash(labels[-1])
    
    w, h = imgui.get_window_size()
    
    implot.push_colormap(implot.Colormap_.hot.value)
    if implot.begin_plot(f"{title}##{name}", ImVec2(w*0.95, h*0.95), implot.Flags_.no_mouse_text.value | implot.Flags_.no_inputs.value):
        implot.setup_axes("", "", implot.AxisFlags_.no_decorations.value, implot.AxisFlags_.no_decorations.value)
        implot.setup_axes_limits(-1.1, 1.1, -1.1, 1.1)
        implot.plot_pie_chart(labels, data, 0, 0, 1, "%.2f%%", implot.PieChartFlags_.normalize.value) 

        implot.end_plot()

@immapp.static(inited=False)
def plot_html(html: Path, label: str = "Presentation") -> None:
    if not html.exists():
        return
    
    statics = plot_html
    if not statics.inited:
        statics.html = html
        statics.quality = 10
        statics.high_quality = False
        statics.flags = imgui_toggle.glowing_style()
        statics.reload = True
        statics.inited = True
    
    if statics.reload:
        with pw() as p:
            browser_type = p.chromium
            browser = browser_type.launch()
            page = browser.new_page()
            page.set_content(html.read_text())
            statics.buffer = page.screenshot(quality=statics.quality, type='jpeg')
            browser.close()
        statics.image = Image.open(io.BytesIO(statics.buffer))
        statics.image = np.array(statics.image.convert('RGB'))
        statics.reload = False

    if statics.html != html:
        statics.inited = False
    
    h = imgui.get_window_size().y
    size = (0, int(h*0.8))
    immvision.image_display(label, statics.image, size, True)
    
    changed, _ = imgui_toggle.toggle("High Quality", statics.high_quality, statics.flags)
    if changed:
        statics.high_quality = not statics.high_quality
        statics.quality = 100 if statics.high_quality else 10
        statics.reload = True

    imgui.same_line()

    if imgui.button("Back"):
        pass
    
    imgui.same_line()

    if imgui.button("Next"):
        pass

@immapp.static(inited=False)
def plot_pdf(pdf: Path, label: str = "Presentation") -> None:
    if not pdf.exists():
        return
    
    statics = plot_pdf
    if not statics.inited:
        statics.pdf = pdf
        statics.images = convert_from_path(statics.pdf.resolve(), size=720, fmt='jpeg')

        statics.selected = 0
        statics.inited = True

    if statics.pdf != pdf:
        statics.inited = False
    
        
    h = imgui.get_window_size().y

    image = np.array(statics.images[statics.selected].convert("RGB"))
    size = (0,int(h*0.8))
    immvision.image_display(label, image, size, True)
    
    if imgui.button("Back"):
        statics.selected -= 1 
        if statics.selected < 0:
            statics.selected = 0 

    imgui.same_line()

    if imgui.button("Next"):
        statics.selected += 1 
        if statics.selected > len(statics.images)-1:
            statics.selected = len(statics.images)-1

