from pathlib import Path
from UltraStarSongFileParser import UltraStarSongFileParser
import requests
from bs4 import BeautifulSoup
import datetime

from song import Song

class TXTDownloader:
    def __init__(self, sessid: str, outdir: Path, cache: bool):
        self.sessid = sessid
        self.outdir = outdir
        self.txtparser = UltraStarSongFileParser()
        self.cache = cache

    def download(self, song: Song):
        if (Path(self.outdir) / f"{song.getFileName_Hash_TXT()}.txt").is_file() and self.cache:
            return

        url = song.txt_link.replace("detail", "gettxt")

        with requests.Session() as s:
            page = s.post(url, data={'wd': 1}, cookies={'PHPSESSID': self.sessid})
            soup = BeautifulSoup(page.content, 'html.parser')
            txt = soup.find(name="textarea").text
            
            lines = []
            for line in txt.split('\n'):
                if line.strip() != "":
                    lines.append(line.replace("\r", ""))
            txt = "\n".join(lines)

            Path(self.outdir).mkdir(parents=True, exist_ok=True)
            with open(Path(self.outdir) / f"{song.getFileName_Hash_TXT()}.txt", "w", encoding="utf-8") as f:
                f.write(txt)
                
    def fix_file(self, file: Path, song: Song):
        txt = self.txtparser.parse_file(str(file), encoding="utf-8")
        txt.mp3 = str(file.with_suffix(".mp3").relative_to(file.parent))
        txt.video = str(file.with_suffix(".mp4").relative_to(file.parent))
        txt.cover = str(file.with_suffix(".jpg").relative_to(file.parent))

        txt.songid = song.uri
        txt.artist = song.artist_name
        txt.title = song.track_name
        
        if not(type(song.gap) == float and str(song.gap) == "nan"):
            txt.gap = song.gap

        if not(type(song.video_gap) == float and str(song.video_gap) == "nan"):
            txt.videogap = song.video_gap

        if not(type(song.start) == float and str(song.start) == "nan"):
            txt.start = song.start

        if not(type(song.gap) == float and str(song.gap) == "nan"):
            txt.end = song.end

        if not(type(song.gap) == float and str(song.gap) == "nan"):
            txt.language = song.language

        if song.release_date != datetime.date.min:
            txt.year = song.release_date

        txt.dump(file)