from flask import Blueprint, render_template, jsonify, request
from .models import Platform
import sqlite3
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

main = Blueprint('main', __name__)

DATABASE = 'platforms.db'

@main.route('/')
def index():
    logger.debug('Handling request for the index page')
    try:
        with sqlite3.connect(DATABASE) as conn:
            cursor = conn.execute('SELECT id, name, image, description, link FROM platforms')
            platforms = [Platform(row[0], row[1], row[2], row[3], row[4]) for row in cursor]
        logger.debug('Fetched platforms: %s', platforms)
        return render_template('index.html', platforms=platforms)
    except Exception as e:
        logger.error('Error fetching platforms: %s', e)
        return 'Error fetching platforms', 500

@main.route('/api/platforms', methods=['GET'])
def get_platforms():
    logger.debug('Handling GET request for /api/platforms')
    try:
        with sqlite3.connect(DATABASE) as conn:
            cursor = conn.execute('SELECT id, name, image, description, link FROM platforms')
            platforms = [{'id': row[0], 'name': row[1], 'image': row[2], 'description': row[3], 'link': row[4]} for row in cursor]
        logger.debug('Fetched platforms: %s', platforms)
        return jsonify(platforms)
    except Exception as e:
        logger.error('Error fetching platforms: %s', e)
        return jsonify({'error': 'Error fetching platforms'}), 500

@main.route('/api/platforms', methods=['POST'])
def add_platform():
    data = request.json
    logger.debug('Handling POST request for /api/platforms with data: %s', data)
    try:
        with sqlite3.connect(DATABASE) as conn:
            conn.execute('INSERT INTO platforms (name, image, description, link) VALUES (?, ?, ?, ?)',
                         (data['name'], data['image'], data['description'], data['link']))
        logger.debug('Platform added successfully')
        return jsonify({'message': 'Platform added successfully'}), 201
    except Exception as e:
        logger.error('Error adding platform: %s', e)
        return jsonify({'error': 'Error adding platform'}), 500

@main.route('/api/platforms/<int:platform_id>', methods=['DELETE'])
def delete_platform(platform_id):
    logger.debug('Handling DELETE request for /api/platforms/%d', platform_id)
    try:
        with sqlite3.connect(DATABASE) as conn:
            conn.execute('DELETE FROM platforms WHERE id = ?', (platform_id,))
        logger.debug('Platform deleted successfully')
        return jsonify({'message': 'Platform deleted successfully'}), 204
    except Exception as e:
        logger.error('Error deleting platform: %s', e)
        return jsonify({'error': 'Error deleting platform'}), 500

@main.route('/api/platform/<int:platform_id>', methods=['GET'])
def get_platform(platform_id):
    logger.debug('Handling GET request for /api/platform/%d', platform_id)
    try:
        with sqlite3.connect(DATABASE) as conn:
            cursor = conn.execute('SELECT id, name, image, description, link FROM platforms WHERE id = ?', (platform_id,))
            row = cursor.fetchone()
            if row:
                platform = {'id': row[0], 'name': row[1], 'image': row[2], 'description': row[3], 'link': row[4]}
                logger.debug('Fetched platform: %s', platform)
                return jsonify(platform)
            else:
                logger.debug('Platform not found')
                return jsonify({'error': 'Platform not found'}), 404
    except Exception as e:
        logger.error('Error fetching platform: %s', e)
        return jsonify({'error': 'Error fetching platform'}), 500

