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

from bottle import request
    
    
from uuid import uuid4
#from paramecio2.libraries.db.extraforms.fileform import FileForm

class FileField(CharField):
    
    def __init__(self, name, save_folder='media/upload/files', sizes=None, module=None, size=255, required=False):
        
        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
                
                
                #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)
        
