from dotenv import load_dotenv
from flask import Flask, render_template, redirect, url_for, request, send_from_directory, session
from pathlib import Path
import os
from datetime import timedelta

# Load environment variables
load_dotenv()

cwd = Path.cwd()
current = ''

# Configuration from environment
SECRET_KEY = os.getenv('FLASK_SECRET_KEY', '_5#y2f231321sadwzx')
USERNAME = os.getenv("USER", 'admin')
PASSWORD = os.getenv("PASS", 'password')
TEMPLATE_FOLDER = 'templates'
INPUT_XML = os.path.join(TEMPLATE_FOLDER, 'input.xml')

# Ensure templates directory exists
os.makedirs(TEMPLATE_FOLDER, exist_ok=True)

app = Flask(__name__, static_url_path='/')
app.secret_key = SECRET_KEY

@app.before_first_request
def make_session_permanent():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=1)

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['uname'] != USERNAME or request.form['pwd'] != PASSWORD:
            error = 'Invalid Credentials. Please try again.'
        else:
            session['logged_in'] = True
            return redirect("/")
    return render_template('login.html', error=error)

@app.route("/")
def loger():
    ll = len(textdisplay)
    if current == True:
        return render_template("form.html", textdisplay=textdisplay1, ll=ll)
    elif 'logged_in' not in session:
        return redirect("/login", code=302)
    else:
        session.clear()
        return render_template("form.html", textdisplay=textdisplay1, ll=ll)

@app.route("/xml/rss/input.xml")
def XML():
    return send_from_directory(TEMPLATE_FOLDER, "input.xml", as_attachment=False)

global textdisplay
global textdisplay1
textdisplay = []
textdisplay1 = []

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']
    global textspl
    global edittitle
    textspl = text.splitlines()
    edittitle = text.splitlines()
    global textdisplay
    global textdisplay1
    textdisplay = []
    textdisplay1 = []
    ErCheck = 0
    textspl = list(filter(None, textspl))
    edittitle = list(filter(None, edittitle))
    for i in range(len(textspl)):
        if not textspl[i]:
            ErCheck += 1
        elif textspl[i] is None:
            ErCheck += 1
        elif textspl[i] == '':
            ErCheck += 1
        elif textspl[i] == "":
            ErCheck += 1
        else:
            textspl[i-ErCheck] = textspl[i]
    textdisplay2 = textspl
    textspl = []
    for i in textdisplay2:
        if i.strip() == '':
            pass
        elif i.strip() == "":
            pass
        else:
            textspl.append(i)
    for i in range(len(textspl)):
        testspldisplay = str(i+1) + ") " + textspl[i]
        testspldisplay1 = textspl[i]
        textdisplay.append(testspldisplay)
        textdisplay1.append(testspldisplay1)
    if text not in [None, "", 0]:
        try:
            if os.path.exists(INPUT_XML):
                os.remove(INPUT_XML)
            with open(INPUT_XML, "a", encoding='utf-8') as o:
                o.write("<rss> \n")
                o.write("   <channel> \n")
                o.write("<title>RSS Feed</title>")
        except Exception as e:
            print(f"No file to delete or error creating file: {e}")
        incEr = 0
        for i in range(len(textspl)):
            if textspl[i] in [None, ""]:
                incEr += 1
            else:
                pass
            edittitle[i] = edittitle[i-incEr] + '\n'
            textspl[i] = "      " + '<title>' + textspl[i-incEr] + '</title> \n'
            print(textspl[i])
            try:
                with open(INPUT_XML, "a", encoding='utf-8') as o:
                    o.write("\t\t<item> \n")
                    o.write(textspl[i])
                    o.write("\t\t\t\t</item>")
            except Exception as e:
                print(f"Error writing item: {e}")
    else:
        print("fail")
    ErCheck = 0
    with open(INPUT_XML, "a", encoding='utf-8') as o:
        session['logged_in'] = True
        o.write("   </channel> \n")
        o.write("</rss>")
    session['logged_in'] = True
    return redirect("/success")

@app.route("/success")
def success():
    return render_template("success.html", textdisplay=textdisplay)

@app.route("/current")
def current():
    return render_template("current.html", textdisplay=textdisplay1)

@app.route('/css/<path:path>')
def send_report(path):
    return send_from_directory('css', path)

@app.route('/fonts/<path:path>')
def send_report1(path):
    return send_from_directory('fonts', path)

@app.route('/images/<path:path>')
def send_report2(path):
    return send_from_directory('images', path)

@app.route('/js/<path:path>')
def send_report3(path):
    return send_from_directory('js', path)

@app.route('/vendor/<path:path>')
def send_report4(path):
    return send_from_directory('vendor', path)

@app.route('/logo/<path:filename>')
def send_logo(filename):
    return send_from_directory(os.path.join(app.root_path, 'templates/logo'), filename)

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'templates/logo'), 'favicon.ico')

if __name__ == '__main__':
    app.run(debug=True, use_reloader=False, host="0.0.0.0", port=80)


