#!/usr/bin/env python3

"""
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
from cuchulu.libraries.db.coreforms import SelectModelForm
from bottle import request

class ParentField(IntegerField):
    """Field used for create fields used by save a parent id from a row in db."""
    
    def __init__(self, name, size=11, required=False, field_name='name'):
        """
        Args:
            name (str): The name of field
            size (int): The size of the new field in database. By default 11.
            required (bool): Boolean for define if field is required or not
            field_name (str): The name of the field used for identify the father row of the db.
        """
        
        super().__init__(name, size, required)
        
        #self.foreignkey=True
        self.indexed=True
        self.field_name=field_name

    def post_register(self):
        
        if self.model!=None:
            self.change_form(SelectModelForm, [self.model, self.field_name, self.model.name_field_id, self.name])
    
    def check(self, value):
        
        value=super().check(value)
        
        if self.model!=None:
            if self.model.updated==True:
                if self.model.name_field_id in self.model.post:
                    #GetPostFiles.obtain_get()

                    #model_id=GetPostFiles.get.get(self.model.name_field_id, '0')
                    
                    model_id=request.query.get(self.model.name_field_id, '0')
                    
                    if model_id==value:
                        self.error=True
                        self.txt_error='A field cannot be its own father'
                        self.required=True
                        value=0
                        return value
                        
                
        return value
