from flask import Flask, request, jsonify
from measurement_data_rdf import measurement_main
from device_data_rdf import device
import requests

app = Flask(__name__)

# Define the base URL and endpoints for the external API
base_url = 'https://api.reinvent.witmo.eu'
device_endpoint_database = '/api/v1/sincere/{database}/device/{device_id}'
meta_data_endpoint = '/api/v1/sincere/{database}/meta_data/{measurement}/{channel_id}'
device_endpoint_channel = '/api/v1/sincere/{database}/device/{device_id}'
meta_data_endpoint_channel = '/api/v1/sincere/{database}/meta_data/{measurement}/{channel_id}'

@app.route('/meteo-device-channels', methods=['POST'])
def meteo_device():
    # Get JSON data from the request
    data = request.get_json()

    if not data or 'database' not in data or 'device_id' not in data:
        return jsonify({"error": "Invalid input, expected JSON with 'database' and 'device_id'"}), 400

    database = data['database']
    device_id = data['device_id']

    # Construct the full URL
    url = base_url + device_endpoint_database.format(database=database, device_id=device_id)

    # Make the GET request to the external API
    response = requests.get(url)

    # Check if the request was successful
    if response.status_code == 200:
        response_data = response.json()
        channels = response_data.get('data', {}).get('channels', [])
        device_data_json = device(channels, database, device_id)
        device_data_json.parse_device_data()
        return jsonify({"device_id": device_id, "channels": channels})
    else:
        return jsonify(
            {"error": f"Failed to retrieve data: {response.status_code} - {response.text}"}), response.status_code

@app.route('/meteo-device-channels', methods=['POST'])
def meteo_device_channels():
    data = request.get_json()
    if not data or 'database' not in data or 'device_id' not in data:
        return jsonify({"error": "Invalid input, expected JSON with 'database' and 'device_id'"}), 400

    database = data['database']
    device_id = data['device_id']
    url = base_url + device_endpoint_channel.format(database=database, device_id=device_id)
    response = requests.get(url)

    if response.status_code == 200:
        response_data = response.json()
        channels = response_data.get('data', {}).get('channels', [])
        return jsonify({"device_id": device_id, "channels": channels})
    else:
        return jsonify({"error": f"Failed to retrieve data: {response.status_code} - {response.text}"}), response.status_code

@app.route('/meta-data', methods=['POST'])
def get_meta_data():
    data = request.get_json()
    if not data or 'database' not in data or 'measurement' not in data or 'channel_id' not in data:
        return jsonify({"error": "Invalid input, expected JSON with 'database', 'measurement', and 'channel_id'"}), 400

    database = data['database']
    measurement = data['measurement']
    channel_id = data['channel_id']
    datetime_from = data.get('datetime_from')
    datetime_end = data.get('datetime_end')
    limit = data.get('limit', 100)
    page = data.get('page', 0)
    pagination = data.get('pagination', True)

    url = base_url + meta_data_endpoint_channel.format(database=database, measurement=measurement, channel_id=channel_id)
    params = {
        'datetime_from': datetime_from,
        'datetime_end': datetime_end,
        'limit': limit,
        'page': page,
        'pagination': str(pagination).lower()
    }

    response = requests.get(url, params=params)

    if response.status_code == 200:
        measurement_data_json = measurement_main(response.json())
        measurement_data_json.parse_measurement_data()
        return jsonify(response.json())
    else:
        return jsonify({"error": f"Failed to retrieve data: {response.status_code} - {response.text}"}), response.status_code

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