
from helper_functions import *
from logger_module.package_logger import print_log
from db.database_operations import DatabaseOperations

class DataPersistence:

    def __init__(self, request, schema, endpoint):
        self.schema = schema
        self.request = request
        self.endpoint = endpoint
        self.body = request.get_json

    def read_persistence_dict(self, schema):
        # endpoint = self.request.full_path.strip('?')
        method = self.request.method.lower()
        persistence_dict = schema.get('paths').get(self.endpoint).get(method).get('persistence')
        return persistence_dict

    def main(self):
        data_list = self.read_persistence_dict(self.schema)
        if data_list:
            status, data = self.execute_persistence(data_list)
            if status:
                return {'cf_code': 'CF200'}
        return {'cf_code': 'CF200'}

    def execute_persistence(self, data):
        for index, objects in enumerate(data):
            txn_commit = True if index == len(data) - 1 else False
            if not objects.get('conditions'):
                self.database_operation(objects, txn_commit)
            else:
                condition = objects.get('conditions')
                condition_result = condition_check(condition, self.body)
                if objects.get(str(condition_result).lower()):
                    self.database_operation(objects.get(str(condition_result).lower()), txn_commit)
        return_data = {'code': 'CF200'}
        return True, return_data

    def database_operation(self, insertion_dict, commit=True):
        try:
            table_name = insertion_dict.get('table')
            status, last_row_id = DatabaseOperations().execute(insertion_dict, self.body)
            if last_row_id and insertion_dict.get('auto_id'):
                set_data(table_name + '_' + insertion_dict.get('auto_id'), last_row_id)
            if insertion_dict.get('resultKey'):
                set_data(insertion_dict.get('resultKey'), last_row_id)
            return
        except Exception as ex:
            print_log(str(ex))
            traceback.print_exc()
