from flask import Flask, request, jsonify
import configparser
import os
from flask_cors import CORS
import logging

app = Flask(__name__)

CORS(app)

CONFIG_FILE_PATH = '/oem/usr/etc/myconf/IMX283_set.conf'
USER_CONFIG_PATH = '/oem/usr/etc/myconf/USER.conf'

config = configparser.ConfigParser()
user_config = configparser.ConfigParser()

def load_config():
    global config
    try:
        config.read(CONFIG_FILE_PATH, encoding='utf-8')
    except Exception as e:
        app.logger.error(f"Error loading config file: {e}")

def load_user_config():
    global user_config
    try:
        user_config.read(USER_CONFIG_PATH,encoding='utf-8')
    except Exception as e:
        app.logger.error(f"Error loading config file: {e}")

load_config()
load_user_config()


@app.route('/getUserConfig',methods=['GET'])
def get_user_config():
    try:
        user_config_dict = {}
        for section in user_config.sections():
            user_config_dict[section] = {}
            for key,value in user_config.items(section):
                user_config_dict[section][key] =value

        return jsonify(user_config_dict),200
    except Exception as e:
        app.logger.error(f"Error reading config: {e}")
        return jsonify({"error": str(e), 'code': 500}), 500


@app.route('/getConfig', methods=['GET'])
def get_config():
    try:
        config_dict = {}
        for section in config.sections():
            config_dict[section] = {}
            for key, value in config.items(section):
                config_dict[section][key] = value

        return jsonify(config_dict), 200
    except Exception as e:
        app.logger.error(f"Error reading config: {e}")
        return jsonify({"error": str(e), 'code': 500}), 500

@app.route('/setUserConfig',methods=['POST'])
def set_user_config():
    try:
        update_config = request.json
        if not update_config:
            return jsonify({"error": "No configuration provided", 'code': 400}), 400
        for section,items in update_config.items():
            if section not in config:
                user_config.add_section(section)
            for key ,value in items.items():
                app.logger.debug(f"Setting {section} -> {key} = {value}")
                user_config.set(section, key, value)
        with open(USER_CONFIG_PATH, 'w', encoding='utf-8') as configfile:
            user_config.write(configfile)

        load_user_config()

        return jsonify({"message": "Configuration updated successfully", 'code': 200}), 200

    except Exception as e:
        app.logger.error(f"Error updating config: {e}")
        return jsonify({"error": str(e), 'code': 500}), 500

@app.route('/setConfig', methods=['POST'])
def set_config():
    try:
        updated_config = request.json
        if not updated_config:
            return jsonify({"error": "No configuration provided", 'code': 400}), 400

        for section, items in updated_config.items():
            if section not in config:
                config.add_section(section)
            for key, value in items.items():
                app.logger.debug(f"Setting {section} -> {key} = {value}")
                config.set(section, key, value)

        with open(CONFIG_FILE_PATH, 'w', encoding='utf-8') as configfile:
            config.write(configfile)

        load_config()

        return jsonify({"message": "Configuration updated successfully", 'code': 200}), 200

    except Exception as e:
        app.logger.error(f"Error updating config: {e}")
        return jsonify({"error": str(e), 'code': 500}), 500

@app.route('/reboot', methods=['POST'])
def reboot():
    try:
        os.system('reboot')  # 重启系统
        return jsonify({'message': 'System is rebooting...', 'code': 200}), 200  # 返回消息和状态码
    except Exception as e:
        return jsonify({'message': 'Error occurred while attempting to reboot.', 'error': str(e), 'code': 500}), 500  # 出错时返回错误信息和状态码

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

