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

#  Copyright © 2009, 2011-2017  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 . import config
from .ext import qt


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 = (1, 1, b'\x00\x00\x00\x00')
        
    def _get_stock_image(self, name):
        filename = os.path.join(self.stock_dir, name)
        self.stock_images[name] = image = qt.load_image_from_file(filename, self.max_size)
        return image
            
    def get_icons(self):
        return sorted(self.stock_images.keys())
            
    def image_from_file(self, filename):
        if not filename:
            image = self.empty_image
        elif filename.startswith('/'):
            image = qt.load_image_from_file(filename, self.max_size)
        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
        

