"""
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 CharField
import re
import ipaddress

check_url = re.compile(
        r'^(?:http|ftp)s?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
        r'localhost|' #localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?' # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

class UrlField(CharField):
    """Field for check and save strings in url format"""
    
    def __init__(self, name, size=1024, required=False):
        
        super().__init__(name, size, required)
        self.jformat='url'
    
    def check(self, value):
        
        self.error=False
        self.txt_error=''
        
        if not check_url.match(value):
            
            self.error=True
            value=""
            self.txt_error='No valid URL format'
            
        return value
        
check_domain=re.compile(r'^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$')

class DomainField(CharField):
    """Field for check and save strings in domain internet format"""
    
    def check(self, value):
        
        self.error=False
        self.txt_error=''
        
        if not check_domain.match(value):
            
            #Check if ip
            try:
        
                value=str(ipaddress.ip_address(value))
        
            except:
            
                self.error=True
                value=""
                self.txt_error='No valid domain or IP format'
            
        return value

#^(https|ssh):\/\/([a-zA-Z0-9\-_]+@)?[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*(:[0-9]+)?\/[a-zA-Z0-9\-_]+(\/[a-zA-Z0-9\-_]+)*(\.git)?$
 
check_git_url=re.compile(r'^(https|ssh):\/\/([a-zA-Z0-9\-_]+@)?[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*(:[a-zA-Z0-9\-_]+)?\/[a-zA-Z0-9\-_]+(\/[a-zA-Z0-9\-_]+)*(\.git)?$')

class GitUrlField(CharField):
    
    """Field for check and save strings in url format for git services"""

    def check(self, value):
        
        self.error=False
        self.txt_error=''
        
        value=value.strip()
        
        if not check_git_url.match(value):
            
            self.error=True
            value=""
            self.txt_error='No valid Git URL format'
            
        return value
