"""
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/>.
"""

import os
import sys
from pathlib import Path
from cuchulu.libraries.db.corefields import CharField
from cuchulu.libraries.db.extraforms.fileform import FileForm
#from paramecio.citoplasma import httputils
from cuchulu.libraries.keyutils import create_key
import traceback

from bottle import request

    
    
from uuid import uuid4

class FileField(CharField):
    """Field for upload and save files in server"""
    
    def __init__(self, name, save_folder='media/upload/files', sizes=None, size=255, required=False):
        """
        Args:
            name (str): The name of field
            save_folder (str): The folder where the files are saved
            sizes (list): In the future will be used for check sizes of files.
            size (int): The size of the new field in database. By default 11.
            required (bool): Boolean for define if field is required or not
        """
        
        super().__init__(name, size, required)
        
        self.yes_prefix=True
                
        self.suffix=''
        
        # Is relative to media folder of paramecio
        
        #if module!=None:
        
        self.save_folder=save_folder
        
        self.file_related=True
        
        self.sizes=sizes
        
        self.name_form=FileForm
        self.extra_parameters=[self.save_folder]

        
    def change_folder(self, folder):
        
        pass
        
    def check(self, value):
        
        files_uploaded=request.files
        
        field_file=self.name+'_file'
        
        #if not change
        
        if not field_file in files_uploaded:
            
            if value=='':
                
                if self.model:
                    
                    if self.model.updated:
                        
                        old_reset=self.model.yes_reset_conditions
                        
                        self.model.yes_reset_conditions=False
                        
                        with self.model.select([self.name]) as cur:
                        
                            for arr_image in cur:
                                
                                if arr_image[self.name]!='':
                                    try:
                                        os.remove(arr_image[self.name])
                                    except:
                                        pass
                                
                                #if arr_image[self.name]!=save_file and arr_image[self.name]!='':
                                
                                #value=arr_image[self.name]
                        
                        self.model.yes_reset_conditions=old_reset
                self.txt_error='Field is empty'
                self.error=True
                
                return ''

            else:
                
                value=os.path.basename(value)
                
                return self.save_folder+'/'+value
            
        
        # Load image file
        
        #file_bytecode=files_uploaded[field_file].file
        
        filename=files_uploaded[field_file].filename
        
        realfilename, ext = os.path.splitext(filename)
        
        prefix=''
        
        if self.yes_prefix==True:
            #prefix=uuid4().hex+'_'
            prefix=create_key(5).replace('/', '-').replace('#', '-')+self.suffix+'_'
        
        filename=prefix+filename
        
        save_file=self.save_folder+'/'+filename
                
        # Save file
        
        try:
            
        #Check if directory exists
            
            if not os.path.isdir(self.save_folder):
                
                # Try create if not
                
                try:
                    
                    p=Path(self.save_folder)
                        
                    p.mkdir(mode=0o755, parents=True)
                
                except:
                    self.error=True
                    
                    self.txt_error='Error: cannot create the directory where save the image.Check permissions,'
                    return ""
            
            #files_uploaded[field_file].save(self.save_folder, overwrite=True)
            
            if os.path.isfile(save_file):
                
                os.remove(save_file)
            
            # Delete old files
            
            if self.model!=None:
                    
                if self.model.updated:
                
                    #old_conditions=self.model.conditions
                    
                    old_reset=self.model.yes_reset_conditions
                    
                    self.model.yes_reset_conditions=False
                    
                    with self.model.select([self.name]) as cur:
                        
                        for arr_file in cur:
                            
                            if arr_file[self.name]!=save_file and arr_file[self.name]!='':
                            
                                if os.path.isfile(arr_file[self.name]):
                            
                                    os.remove(arr_file[self.name])
                    
                    self.model.yes_reset_conditions=old_reset
                
                # Save file
                
                files_uploaded[field_file].save(save_file)
                
                #self.model.conditions=old_conditions
            
            return save_file

        except:
            
            self.error=True
            self.txt_error='Error: cannot save the image file, Exists directory for save the file? '+traceback.format_exc()
            print(traceback.format_exc())
            return ""

    def show_formatted(self, value):
        
        return os.path.basename(value)
        
