from django.shortcuts import render
from django.http import HttpResponse
from InvertedIndexSimulator.inverted import main
import pandas as pd 
import xml.etree.ElementTree as et

def home(request):
    return render(request, 'apps/home.html')

def dataframe(request):
    
    parse_data = et.parse("InvertedIndexSimulator/data/dataset_STBI.xml")
    data = parse_data.getroot() 
    
    df_cols = ["DOCNO", "SONG", "ARTIST", "LYRICS"]
    rows = []

    for node in data: 
        s_docno = node.find("DOCNO").text if node is not None else None
        s_song = node.find("SONG").text if node is not None else None
        s_artist = node.find("ARTIST").text if node is not None else None
        s_lyrics = node.find("LYRICS").text if node is not None else None
        
        rows.append({"DOCNO": s_docno, "SONG": s_song, "ARTIST": s_artist, "LYRICS": s_lyrics})
    
    DataFrame = pd.DataFrame(rows, columns = df_cols)
    
    dictionary = DataFrame.set_index('DOCNO').T.to_dict('list')
    
    nilai    = list(dictionary.values())
    nomornya = list(dictionary.keys())
    
    lagunya  = [sublist[0] for sublist in nilai]
    artisnya = [sublist[1] for sublist in nilai]
    liriknya = [sublist[2] for sublist in nilai]
    
    context = {"DOCNO": nomornya, "SONG": lagunya, "ARTIST": artisnya, "LYRICS": liriknya}
    
    return render(request, 'apps/dataframe.html', context)

def preprocessing(request):
    return render(request, 'apps/preprocessing.html')

def indexing(request):
    return render(request, 'apps/indexing.html')
    
def index(request):
    return render(request, 'apps/index.html')


def lyric(request,id):
    
    text, judul = main.detail(id)
    content={
        'no': id,
        'judul':judul,
        'text':text
    }
    return render(request, 'apps/lyric.html', content)

def result(request):
    #%%
    # proximity_index = collections.OrderedDict(sorted(proximity_index.items()))
    # for key, value in proximity_index.items():
    #     # print (key, value)
    
    if request.method == 'POST':
        query = request.POST['querysearch']
        hasil= main.main(query)

        content={
            'hasil':hasil,
            'query':query
        }
        
        return render(request, 'apps/result.html', content)
