from flask import Flask, render_template, request, jsonify
from datetime import datetime
import subprocess
import os

app = Flask(__name__)

running_processes = {}

def run_command(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout, stderr = process.communicate()
    return stdout.decode('utf-8') + stderr.decode('utf-8')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/run-script', methods=['POST'])
def run_script():
    script_name = request.form.get('script_name')

    # Commands for scripts
    script_commands = {
        'Bein_Batch': 'bash /media/Beinchannels/Bein_Batch.sh',
        'OSN_Batch': 'bash /media/OSN/OSN_Batch.sh',
        'EPG_MTV_LiveHD': 'python3 /media/EPG-MTV-LiveHDScript.py',
        'RehostWeekly': 'bash /media/run_RehostWeekly.sh',
        'Translation': 'bash /media/run_translation.sh',
        'TranslationWeekly': 'bash /media/run_translationWeekly.sh',
        'GeoNews': 'python3 /media/GeoNews/GeoNews.py'
    }

    if script_name in script_commands:
        command = script_commands[script_name]
        output = run_command(command)
        return jsonify({'output': output})
    else:
        return jsonify({'error': 'Invalid script name'}), 400

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    channel = request.form.get('channel')

    # Save the file to the uploads folder
    file_path = os.path.join('/var/www/html/ChannelSelection/uploads', file.filename)
    file.save(file_path)

    # Commands for file conversion (each channel uses different script)
    conversion_commands = {
        'GeoEnt': f'python3 /media/GeoEPG/B.py {file_path}',
        'GeoKahani': f'python3 /media/GeoKahaniEPG/B.py {file_path}',
        'HumNews': f'python3 /media/HumNews/HumNews.py {file_path}',
        '365News': f'python3 /media/365News/365News.py {file_path}',
        'AAN_TV_EPG': f'python3 /media/AAN_TV_EPG/AAN_TV.py {file_path}',
        'SetEntertainment': f'python3 /media/SetEntertainment/SetEntertainment.py {file_path}',
        'AAJNews': f'python3 /media/AAJNews/AAJNews.py {file_path}',
        'AAJ_Ent': f'python3 /media/AAJ_Ent/AAJ_Ent.py {file_path}',
        'GreenEnt': f'python3 /media/GreenEnt/GreenEnt.py {file_path}'

    }

    if channel in conversion_commands:
        command = conversion_commands[channel]
        output = run_command(command)
        return jsonify({'output': output})
    else:
        return jsonify({'error': 'Invalid channel selected'}), 400

@app.route('/run-script-with-date', methods=['POST'])
def run_script_with_date():
    data = request.get_json()
    script_name = data.get('script_name')
    date = data.get('date')

    if not date:
        return jsonify({'error': 'Date is required'}), 400
   
    # Define script-specific date formats
    if script_name == 'HumTV_Batch':
        formatted_date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y%m%d')
    else:
        formatted_date = date  # Use the default 'YYYY-MM-DD' for other scripts

    # Commands for scripts that need a date parameter
    script_commands_with_date = {
        'PTVhtlmTOXMLDate': f'python3 /media/PTVSports/PTVhtlmTOXMLDate.py {formatted_date}',
        'AAJEnt': f'python3 /media/AAJEnt/AAJEnt.py {formatted_date}',
        'ExpressEnt': f'python3 /media/ExpressENT/ExpressEnt.py {formatted_date}',
        'InternationalNews': f'python3 /media/InternationalNews/InternationalNews.py {formatted_date}',
        'Urdu1': f'python3 /media/Urdu1/Urdu1.py {formatted_date}',
        'PTVWorld': f'python3 /media/PTVWorld/PTVWorld.py {formatted_date}',
        'PTVNews': f'python3 /media/PTVNews/PTVNews.py {formatted_date}',
        'PTVHome': f'python3 /media/PTVHome/PTVHome.py {formatted_date}',
        'HumTV_Batch': f'bash /media/HumTV/HumTV_Batch.sh {formatted_date}'

    }

    if script_name in script_commands_with_date:
        command = script_commands_with_date[script_name]
        output = run_command(command)
        return jsonify({'output': output})
    else:
        return jsonify({'error': 'Invalid script name or script does not accept date'}), 400


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