from giara.constants import RESOURCE_PREFIX
from gi.repository import Gtk, GdkPixbuf, Gdk
from giara.confManager import ConfManager
import cairo


class PictureView(Gtk.DrawingArea):
    def __init__(self, path, is_video=False, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.confman = ConfManager()
        self.is_video = is_video
        self.path = path

        self.video_icon_pixbuf = None
        self.video_icon_surface = None
        if self.is_video:
            self.video_icon_pixbuf = (
                GdkPixbuf.Pixbuf.new_from_resource(
                    f'{RESOURCE_PREFIX}/icons/video-icon.svg'
                )
            )
            self.video_icon_surface = Gdk.cairo_surface_create_from_pixbuf(
                self.video_icon_pixbuf, 1, None
            )
        self.pixbuf = GdkPixbuf.Pixbuf.new_from_file(self.path)
        self.img_surface = Gdk.cairo_surface_create_from_pixbuf(
            self.pixbuf, 1, None
        )
        self.old_scaled_surface = None
        self.old_sf = -1

    def get_useful_height(self, width):
        aw = width
        pw = self.pixbuf.get_width()
        ph = self.pixbuf.get_height()
        return aw/pw * ph

    def get_mscale_factor(self, width):
        return width / self.pixbuf.get_width()

    def do_draw(self, context):
        width = self.get_allocated_width()
        x_pos = 0
        if self.confman.conf['max_picture_width'] > 0:
            if width > self.confman.conf['max_picture_width']:
                width = self.confman.conf['max_picture_width']
                x_pos = (self.get_allocated_width()//2)-(width//2)
        height = self.get_useful_height(width)
        sf = self.get_mscale_factor(width)
        if sf != self.old_sf:
            self.old_sf = sf
            wsf = self.get_scale_factor()
            self.old_scaled_surface = context.get_target().create_similar(
                cairo.Content.COLOR_ALPHA,
                int(wsf*width),
                int(wsf*height)
            )
            self.old_scaled_surface.set_device_scale(wsf, wsf)
            scaled_ctx = cairo.Context(self.old_scaled_surface)
            scaled_ctx.scale(sf, sf)
            scaled_ctx.set_source_surface(self.img_surface, x_pos, 0)
            scaled_ctx.paint()
        context.set_source_surface(self.old_scaled_surface, x_pos, 0)
        context.paint()
        self.set_size_request(-1, height)

        if self.is_video:
            self.old_scale_factor = 1
            context.set_source_surface(
                self.video_icon_surface,
                x_pos+(width//2)-(self.video_icon_pixbuf.get_width()//2),
                (height//2)-(self.video_icon_pixbuf.get_height()//2)
            )
            context.paint()
