"""
Cuchulufm is a series of wrappers for bottle, mako and others and construct a simple headless cms.

Copyright (C) 2023 Antonio de la Rosa Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

from cuchulu.libraries.db.corefields import IntegerField
try:
    from cuchulu.libraries.db.extraforms.colorform import ColorForm
except:
    class ColorForm:
        pass

class ColorField(IntegerField):
    """Simple field for save colors in hexadecimal format."""

    def __init__(self, name, size=11, required=False):
        super().__init__(name, size, required)
        
        self.name_form=ColorForm
        self.jtype='string'
        self.jexample='#f0f0f0'
    
    def check(self, value):
        
        value=str(value).replace('#', '0x')
        
        value=int(value, 16)
        
        if value<0 or value>0xffffff:
            value=0
            
        return value
    def get_hex_color(self, value):
        
        value=str(hex(int(value))).replace('0x', '')
        
        c=len(value)
        
        if(c<6):
            repeat=6-c
            value=('0'*repeat)+value
            
        value='#'+value
        
        return value

    def show_formatted(self, value):

        value=str(hex(int(value))).replace('0x', '')
        
        c=len(value)
        
        if(c<6):
            repeat=6-c
            value=('0'*repeat)+value
            
        value='#'+value

        return '<div style="width:50px;height:50px;background-color:%s;"></div>' % value;
