from flask import Flask, render_template, request, jsonify, redirect, url_for
from flask_cors import CORS
from database import init_db, add_country, remove_country, get_all_countries, save_highlight_color, get_highlight_color, save_map_type, get_map_type, create_shared_map, get_shared_map
import requests

app = Flask(__name__)
CORS(app)  # 启用CORS
init_db()

@app.route('/')
def index():
    app.logger.info('访问主页')
    return render_template('index.html')

@app.route('/countries', methods=['GET'])
def get_countries():
    app.logger.info('获取国家列表')
    countries = get_all_countries()
    app.logger.info(f'返回的国家列表: {countries}')
    return jsonify(countries)

@app.route('/add_country', methods=['POST'])
def add_country_route():
    app.logger.info('添加国家')
    country = request.json['country']
    app.logger.info(f'尝试添加国家: {country}')
    # 验证国家名称
    response = requests.get(f"https://restcountries.com/v3.1/name/{country}")
    if response.status_code == 200:
        add_country(country)
        app.logger.info(f'成功添加国家: {country}')
        return jsonify({"success": True, "message": "国家添加成功"})
    else:
        app.logger.warning(f'无效的国家名称: {country}')
        return jsonify({"success": False, "message": "无效的国家名称"}), 400

@app.route('/remove_country', methods=['POST'])
def remove_country_route():
    app.logger.info('删除国家')
    country = request.json['country']
    remove_country(country)
    return jsonify({"success": True})

@app.route('/test')
def test():
    return "测试路由正常工作"

@app.route('/save_highlight_color', methods=['POST'])
def save_highlight_color_route():
    color = request.json['color']
    save_highlight_color(color)
    return jsonify({"success": True})

@app.route('/get_highlight_color', methods=['GET'])
def get_highlight_color_route():
    color = get_highlight_color()
    return jsonify({"color": color})

@app.route('/save_map_type', methods=['POST'])
def save_map_type_route():
    map_type = request.json['mapType']
    save_map_type(map_type)
    return jsonify({"success": True})

@app.route('/get_map_type', methods=['GET'])
def get_map_type_route():
    map_type = get_map_type()
    return jsonify({"mapType": map_type})

@app.route('/share_map', methods=['POST'])
def share_map():
    data = request.json
    countries = data['countries']
    highlight_color = data['highlight_color']
    map_type = data['map_type']
    map_id = create_shared_map(countries, highlight_color, map_type)
    return jsonify({"success": True, "share_url": f"/maps/{map_id}"})

@app.route('/maps/<map_id>')
def view_shared_map(map_id):
    shared_map = get_shared_map(map_id)
    if shared_map:
        return render_template('shared_map.html', map_data=shared_map)
    else:
        return "Map not found", 404

if __name__ == '__main__':
    app.run(debug=True, port=5001)
