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

#  Pybik -- A 3 dimensional magic cube game.
#  Copyright © 2009, 2011-2013  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/>.

# Ported from GNUbik
# Original filename: textures.c
# Original copyright and license: 2003  John Darrington, GPL3+


import os
from glob import glob

# pylint: disable=W0614,W0401
from PyQt4.QtCore import Qt
from PyQt4.QtGui import *
# pylint: enable=W0614,W0401

from . import config

class Textures (object):
    max_size = 256
    stock_dir = os.path.join(config.UI_DIR, 'images')
    
    def __init__(self):
        self.stock_files = sorted(os.path.basename(f) for f in glob(os.path.join(self.stock_dir, '*')))
        self.stock_pixbuf = {'': self.create_dummy()}
        
    def get_stock_pixbuf(self, name):
        try:
            return self.stock_pixbuf[name]
        except KeyError:
            if name not in self.stock_files:
                return self.stock_pixbuf['']
            filename = os.path.join(self.stock_dir, name)
            self.stock_pixbuf[name] = pixbuf = self.create_pixbuf_from_file(filename)
            return pixbuf
            
    @classmethod
    def create_pixbuf_from_file(cls, filename):
        image = QImage(filename)
        # We must scale the image,  because Mesa/OpenGL insists on it being of size
        # 2^n ( where n is integer )
        width = image.width()
        height = image.height()
        scaled_width = cls.max_size
        while scaled_width > width:
            scaled_width //= 2
        scaled_height = cls.max_size
        while scaled_height > height:
            scaled_height //= 2
        return image.scaled(scaled_width, scaled_height, transformMode=Qt.SmoothTransformation)
        
    @classmethod
    def create_dummy(cls):
        image = QImage(1, 1, QImage.Format_ARGB32)
        image.fill(0)
        return image
        
textures = Textures()

