from dotenv import load_dotenv
import os
import time

load_dotenv()

def ensure_folder_exists(folder_path):
    os.makedirs(folder_path, exist_ok=True)

ADR = os.getenv("SERVER_ADDRESS", "http://localhost")
FinalFolder = os.getenv("TICKER_FOLDER", "./TickerFiles/")
XmlRoute = ADR + os.getenv("XML_ROUTE", "./xml/rss/input.xml")
SLEEP_SECONDS = int(os.getenv("SLEEP_SECONDS", "30"))


ensure_folder_exists(FinalFolder)

def get_posts_details(rss=None):
    if rss is not None:
        import feedparser
        blog_feed = feedparser.parse(rss)
        posts = blog_feed.entries
        post_list = []
        for post in posts:
            temp = {}
            temp["title"] = getattr(post, "title", "")
            post_list.append(temp)
        return post_list
    else:
        return None

while True:
    posts_details = get_posts_details(rss=XmlRoute)
    try:
        for i in os.listdir(FinalFolder):
            try:
                os.remove(os.path.join(FinalFolder, i))
            except Exception as e:
                print(f"No file to delete: {e}")
    except Exception as e:
        print(f"Error listing directory: {e}")

    x = 0
    print("---------------------------------------------------------------------")
    incEr = 0
    if posts_details:
        for i, post in enumerate(posts_details):
            title = post.get('title', '')
            x += 1
            print(f"{x-incEr}) {title}")
            if not title:
                incEr += 1
                continue
            filename = f"{i+1-incEr:02}.txt"
            try:
                with open(os.path.join(FinalFolder, filename), "w", encoding='utf-8') as o:
                    o.write(title)
            except Exception as e:
                print(f"Error writing file {filename}: {e}")
    print("number of files: ", x - incEr)
    
    time.sleep(SLEEP_SECONDS)