#!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2024 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

import os
import json
from . import schema_utils as su


class AssociatedChecker:
    def __init__(self, json_schemas_dir, schema_dir):
        self.json_schemas_dir = json_schemas_dir
        self.schema_dir = schema_dir

    def check_jsonschemas(self, schema_name):
        schema_dir = os.path.join(self.json_schemas_dir, schema_name)
        if not os.path.isdir(schema_dir):
            su.ep.print_errorlog('3-1',
                                 'None',
                                 os.path.join(self.schema_dir, schema_name + '.json'),
                                 'None',
                                 'None',
                                 'None',
                                 'schema文件没有定义JSONSchemas节点',
                                 'None',
                                 'None')
            return False
        index_path = os.path.join(schema_dir, 'index.json')
        try:
            with open(index_path, 'r') as file:
                content = file.read()
                if not content.strip():
                    su.ep.print_errorlog('3-1',
                                 'None',
                                 os.path.join(self.schema_dir, schema_name + '.json'),
                                 'None',
                                 'None',
                                 'None',
                                 'schema文件没有定义JSONSchemas节点',
                                 'None',
                                 'None')
                    return False
                json.loads(content)
        except (json.JSONDecodeError, IOError):
            su.ep.print_errorlog('3-1',
                                 'None',
                                 os.path.join(self.schema_dir, schema_name + '.json'),
                                 'None',
                                 'None',
                                 'None',
                                 'schema文件定义JSONSchemas节点内容有误',
                                 'None',
                                 'None')
            return False
        return True
    
    def check(self, schema_name):
        return self.check_jsonschemas(schema_name)