#!/usr/bin/env python

from media import Media
from get_image_tag import get_exif_tag
from PIL import Image
from raw_photo import get_raw_image_dimensions

class ImgPreview:
    def __init__(self,*args,**kwargs):
        super(ImgPreview,self).__init__()
        self.args = args
        self.kwargs = kwargs
        self.file = kwargs['file']
        self.event = kwargs['event']
        self.config = kwargs['config']
        self.m = Media(self.file,
                       self.event,
                       self.config)
        self.file_type = self.m.file_type
        self.is_jpg = False
        self.is_raw = False

        if self.file_type == 'image':
            self._img_preview()
            print(f'size: {self.size}')
            print(f'dpi: {self.dpi}')
            print(f'iso: {self.iso}')
            print(f'lens: {self.lens}')
            print(f'zoom: {self.zoom}')
            print(f'camera: {self.camera}')
            print(f'aperture: {self.aperture}')
            print(f'mpixels: {self.mpixels}')

    def _img_preview(self):
        self.dtc = f'{self.m.capture_date[0]}/{self.m.capture_date[1]}/{self.m.capture_date[2]}'
        self.dpi = get_exif_tag(self.file, "xresolution")
        self.iso = get_exif_tag(self.file, 'iso')
        self.aperture = get_exif_tag(self.file, 'fnumber')
        self.camera = get_exif_tag(self.file,'cameramodelname')
        if self.camera is None:
            self.camera = get_exif_tag(self.file,'image model')
        self.lens = get_exif_tag(self.file,'lensmodel')
        self.zoom = get_exif_tag(self.file,'focallength')

        if self.file.lower().endswith("jpg") \
                or self.file.lower().endswith("jpeg"):
            self._jpg_preview()
        else:
            self._raw_preview()

        self.size = f'{self.width}x{self.height}'
        if self.width is not None \
            and self.height is not None:
            self.mpixels = round((self.width * self.height) / 1000000, 1)
        else:
            self.mpixels = 'Unknown :('

    def _jpg_preview(self):
        self.is_jpg = True
        img = Image.open(self.file)
        self.width = img.width
        self.height = img.height

    def _raw_preview(self):
        self.is_raw = True
        self.width = get_raw_image_dimensions(self.file)[1]
        self.height = get_raw_image_dimensions(self.file)[0]