import gradio as gr
import requests
import xmltodict
import bs4
import lxml
import json



def read_rss():
    f = open('feeds_sorted.json')
    data = json.load(f)
    #with open('tmp.json','w') as f:
    out = json.dumps(data, indent=4)
    #f.close()
    return data, out

def find_rss(rss_url):
    json_box=[]
    json_dict={}
    json_dict_other={}
    r = requests.get(f'{rss_url}') 
    soup = bs4.BeautifulSoup(r.content,'lxml')
    for i,p in enumerate(soup.find_all("a")):
        try:
            if ".xml" in p['href'] or ".json" in p['href'] or ".rss" in p['href']:
                print (p['href'])
                json_dict[str(p.text)]=p['href']
            else:
                json_dict_other[str(p.text)]=p['href']
                
        except Exception:
            pass
    json_box.append(json_dict)
    json_box.append(json_dict_other)
    yield json_box

def get_rss(rss_url):
    r = requests.get(f'{rss_url}') 
    if ".json" in rss_url:
        lod = json.loads(r.text)
    if ".xml" in rss_url:
        lod = xmltodict.parse(r.text)
    if ".rss" in rss_url:
        lod = xmltodict.parse(r.text)        
    return lod

with gr.Blocks() as app:
    with gr.Row():
        rss_search = gr.Textbox(label="search rss (xml,json)")
        search_btn=gr.Button("find rss")
    with gr.Row():
        rss = gr.Textbox(label="rss")
        btn = gr.Button("load rss")
    r_btn=gr.Button("read")
    with gr.Row():
        out_json = gr.JSON()
        fil = gr.Textbox()
    r_btn.click(read_rss,None,[out_json,fil])
    search_btn.click(find_rss,rss_search,out_json)
    btn.click(get_rss,rss,out_json)
app.launch()