
import sqlite3
import html
import datetime
from song_tools import *
from DBtools import *
from callAPI import *

file_path = "./song-export/"

def writeSong(song, arr):
    song_title = song['attributes']['title']
    song_id = song['id']
    arrangment_id = arr['id']
    song_url = "https://services.planningcenteronline.com/songs/"+song_id+"/arrangements/" + arrangment_id
    arrangement_name = arr['attributes']['name']
    filename = song_title
    if arrangement_name != "Default Arrangement":
        filename += " (" + arrangement_name + ")"

    filename = sanitize_filename(filename)
    author = song['attributes']['author']
    verseOrder = (' '.join(arr['attributes']['sequence_short'])).lower()
    lyrics = parse_lyrics(arr['attributes']['lyrics'], "")
    now = datetime.datetime.now()
    s = "%Y-%m-%dT%H:%M+04:00"
    time_exported = now.strftime(s)
   
    with open(file_path + filename + ".xml", 'w') as file:
        # Write the text to the file
        #file.write(arrangment['attributes']['lyrics'])
        #songcheck_result['uniqe_verse_elements'] 

       
        if author is None or len(author) == 0:
            author = ""
        
        author = sanitize_filename(author)
        arrangement_name = sanitize_filename(arrangement_name)


        output = "<?xml version='1.0' encoding='UTF-8'?>\n"
        output += "<song xmlns=\"http://openlyrics.info/namespace/2009/song\" " \
                "version=\"0.9\" " \
                "createdIn=\"Bogafjell Kirke - Planning Center Song Exporter\" " \
                "modifiedIn=\"Bogafjell Kirke - Planning Center Song Exporter\" " \
                "modifiedDate=\""+time_exported+"\">\n" \
                "\t<properties>\n\t\t<titles>\n\t\t\t<title>" + filename + "</title>\n\t\t</titles>"
        output += "\n\t\t<verseOrder>" + verseOrder + "</verseOrder>"
        output += "\n\t\t<author>" + author + "</author>"
        output += "\n\t\t<variant>" + arrangement_name + "</variant>"
        output += "\n\t\t<comments><comment>" + song_url + "</comment></comments>"
        
        output += "\n\t</properties>"
        output += "\n\t<lyrics>"

        for verse in lyrics:
            #for part in verse:
            output += "\n\t\t <verse name=\"" + verse['verse_type'] + verse['verse_number'] + "\">"
            output += "\n\t\t\t<lines>" + (verse['verse_text']).replace("\n", "<br/>") + "</lines>"
            #output += "\n\t\t\t<lines>" + verse['verse_text'] + "</lines>"
            output += "\n\t\t </verse>"
        output += "\n\t</lyrics>"
        output += "\n</song>"
        file.write(output)

def sanitize_filename(filename):
    # List of disallowed characters (for both Windows and Unix/Linux)
    disallowed_chars = '<>:"/\\|?*&'

    # Replace each disallowed character with an empty string
    for char in disallowed_chars:
        filename = filename.replace(char, '')

    return filename

def write_songs_to_open_lyrics():
    arrangment_list = json.loads(return_arrangments_which_are_ok())
    counter = 0
    for arr in arrangment_list:
        counter=counter+1
        print (f"{counter} - Arrangementnavn: {arr['song_id']}")
        song_data = request_song(arr['song_id'])
        arrangement_data = request_arrangment(arr['song_id'], arr['arrangement_id'])
        writeSong(song_data['data'], arrangement_data['data'])




# def create_html_with_check_all_song_result_json(song_data):
#     #song_data = json.load(data)
#     # Starting the HTML document
#     html_table = '''
#     <!DOCTYPE html>
#     <html lang="en">
#     <head>
#         <meta charset="UTF-8">
#         <title>Song Table</title>
#     </head>
#     <body>
#         <table border="1">
#             <tr>
#                 <th>Song title</th>
#                 <th>Arrangement name</th>
#                 <th>Has Lyrics</th>
#                 <th>Lyrics formatting</th>
#                 <th>Verse check result</th>
#                 <th>unike vers elements</th>
#                 <th>linjelengde</th>
#                 <th>Added by</th>
#                 <th>Created at</th>
#             </tr>
#     '''

#     # Adding each song to the table
#     for song in song_data:
        
#         if(song['all_ok'] == "False"):
#             verse_result = " ".join(song['verse_result'])
#             trimmed_verse_result = verse_result[:100]
#             html_table += f'''
#                 <tr>
#                     <td>{song['song_title']}</td>
#                     <td><a href="{song['song_url']}" target='_blank'>{song['arrangment_name']}</a></td>
#                     <td>{song['has_lyrics']}</td>
#                     <td>{song['verse_start']}</td>
#                     <td>{trimmed_verse_result}</td>
#                     <td>{song['uniqe_verse_elements']}</td>
#                     <td>{song['line_lenght']}</td>
                    
#                     <td>{song['created_by']}</td>
#                     <td>{song['created_at']}</td>
                    
#                 </tr>
#             '''

#     # End of the HTML table
#     html_table += '''
#         </table>
#     </body>
#     </html>
#     '''
#     # Writing the HTML content to a file
#     with open('song_list.html', 'w') as file:
#         file.write(html_table)

#     print("HTML file created successfully.")
# #def fix_verse(lyrics):

# #not in use
# def createHTMLfileFromDB():
#     # Connect to the SQLite database
#     conn = sqlite3.connect("song_check_data.db")
#     cursor = conn.cursor()

#     # Query the data from the 'songs' table
#     cursor.execute("SELECT * FROM songs")
#     data = cursor.fetchall()

#     # Create an HTML file and write the table to it
#     with open("songs_table_from_db.html", "w") as html_file:
#         html_file.write("<html><head><title>Songs Table</title></head><body>")
#         html_file.write("<table border='1'>")
        
#         # Write table headers
#         headers = [description[0] for description in cursor.description]
#         html_file.write("<tr>")
#         for header in headers:
#             html_file.write(f"<th>{html.escape(header)}</th>")
#         html_file.write("</tr>")
        
#         # Write table rows
#         for row in data:
#             html_file.write("<tr>")
#             for cell in row:
#                 html_file.write(f"<td>{html.escape(str(cell))}</td>")
#             html_file.write("</tr>")
        
#         html_file.write("</table></body></html>")

#     # Close the database connection
#     conn.close()

#     print("HTML table has been created in songs_table.html")
