from paramecio2.libraries.db.webmodel import WebModel, PhangoField
import sys
try:
    
    import ujson as json
except:
    import json

class JsonField(PhangoField):
    """Field for save json datatype values"""
        
    def __init__(self, name, field_type, required=False):
        """
        Args:
            name (str): The name of field
            field_type (PhangoField): The type of PhangoField for save in JsonField
            required (bool): Boolean for define if field is required or not
        """
        
        super().__init__(name, required)
        
        self.field_type=field_type
    
        self.error_default='Sorry, the json dict is invalid'

        self.set_default='NOT NULL'
    
    def check(self, value):
        
        if type(value).__name__=='str':
            try:
                
                value=json.loads(value)
                
            except json.JSONDecodeError:
                
                value={}
                self.error=True
                self.txt_error=self.error_default
                
        elif type(value).__name__!='dict':
            
            value={}
            self.error=True
            self.txt_error=self.error_default
            
        for k,v in value.items():
            
            value[k]=self.field_type.check(v)
            
        final_value=json.dumps(value)
        
        #final_value=WebModel.escape_sql(final_value)
        
        return final_value

    def get_type_sql(self):

        return 'LONGTEXT '+self.set_default
    
    def show_formatted(self, value):
        
        return ", ".join(value)

# You need check the values previously.     

class JsonValueField(PhangoField):
    """Field for save json mixed values. You need check the values previously, the field only check values for prevent sql injections."""
    
    def __init__(self, name, required=False):
        
        super().__init__(name, required)
    
        self.error_default='Sorry, the json dict is invalid'
        self.default_value={}

        #self.set_default='NOT NULL'
    
    def get_type_sql(self):

        return 'JSON'
    
    def check(self, value):
    
        try:
            final_value=json.dumps(value)
        
        except json.JSONDecodeError:
                
            final_value='{}'
            self.error=True
            self.txt_error=self.error_default            
        
        return final_value
