#-*- coding:utf-8 -*-

#  Copyright © 2009, 2011-2015  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.


import os
from glob import glob
from collections import defaultdict

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QImage, QPixmap

from . import config


class Textures:
    max_size = 256
    stock_dir = os.path.join(config.UI_DIR, 'images')
    
    def __init__(self):
        self.stock_images = {os.path.basename(f): None for f in glob(os.path.join(self.stock_dir, '*'))}
        self.empty_image = QImage(1, 1, QImage.Format_RGBA8888)
        self.empty_image.fill(0)
        
    def _get_stock_image(self, name):
        filename = os.path.join(self.stock_dir, name)
        self.stock_images[name] = image = self._load_image_from_file(filename)
        return image
            
    @classmethod
    def _load_image_from_file(cls, filename):
        image = QImage(filename)
        if image.isNull():
            return None
        # scale the image to size 2^n for OpenGL
        width = image.width()
        height = image.height()
        if width < 1 or height < 1:
            return None
        scaled_width = cls.max_size
        while scaled_width > width:
            scaled_width //= 2
        scaled_height = cls.max_size
        while scaled_height > height:
            scaled_height //= 2
        image = image.scaled(scaled_width, scaled_height, transformMode=Qt.SmoothTransformation)
        image = image.convertToFormat(QImage.Format_RGBA8888)
        return image
        
    def get_icons(self):
        for filename, image in sorted(self.stock_images.items()):
            if image is None:
                image = self._get_stock_image(filename)
            if image is not None:
                yield filename, QIcon(QPixmap(image))
            
    def image_from_file(self, filename):
        if not filename:
            image = self.empty_image
        elif filename.startswith('/'):
            image = self._load_image_from_file(filename)
        else:
            try:
                image = self.stock_images[filename]
                if image is None:
                    image = self._get_stock_image(filename)
            except KeyError:
                image = None
        return image
        
        
class FaceTheme:
    __slots__ = 'color imagemode image texrect'.split()
    
    
class Theme:
    textures = Textures()
    
    def __init__(self):
        self.faces = defaultdict(FaceTheme)
        
    def load_face_image(self, facekey, filename):
        image = self.textures.image_from_file(filename)
        if image is None:
            self.faces[facekey].image = self.textures.empty_image
            return False
        self.faces[facekey].image = image
        return True
        

