# -*- coding: utf-8 -*-
import subprocess
import os
import re

location_script = os.getcwd()
homepath = os.path.expanduser(os.getenv("USERPROFILE"))
desktoppath = "Desktop"


class Twitch:

    def run(self, cmd):
        try:
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
        except:
            pass
        return proc.returncode, stdout, stderr

    def get_path_streamers(self, streamers):
        os.chdir(os.path.join(homepath, desktoppath))
        for streamer in streamers:
            output = os.fsdecode(subprocess.check_output(["twitch-dl", "videos", streamer]))
            with open(''.join((streamer, ".txt")), "w") as _file:
                _file.write(output)

    def read_list_videos(self, streamers):
        not_words_in_the_list = [
            "There are more",
            "Increase",
            "mVideo",
            "--"
        ]
        os.chdir(os.path.join(homepath, desktoppath))
        for streamer in streamers:
            filename = ''.join((streamer, '.txt'))
            with open(filename, "r") as _file:
                tex_nv = _file.readlines()

            cont = 1
            for palavra in tex_nv:
                if len(palavra) > 1:
                    if "Published" or 'Showing' in palavra:
                        print(cont, palavra)
                    elif palavra not in not_words_in_the_list and palavra not in "\n" and not palavra.startswith('mV'):
                        cortar_palavras = palavra.split()
                        juntar_palavras = ''
                        for pal in cortar_palavras:
                            juntar_palavras += ''.join(re.findall(r'[a-zA-Z]', pal))
                            juntar_palavras += ' '
                        print(cont, juntar_palavras)
                    cont += 1


if __name__ == "__main__":
    streamers = ["marinaul", "pokemaobr"]
    twitch = Twitch()
    # twitch.get_path_streamers(streamers)
    twitch.read_list_videos(streamers)

# for palavra in tex_nv:
#     if 'marinaul' not in palavra and 'There are more' not in palavra\
#             and 'Loading' not in palavra and '-----' not in palavra\
#             and palavra not in '\n':
#         print(palavra.split())

# nro_video_para_baixar = 821404850
# print(os.getcwd())
# code, out, err = run(["twitch-dl", "download", f"{nro_video_para_baixar}"])
# print(code, out, err)
# f'twitch-dl download {nro_video_para_baixar}'
# subprocess.check_output(
#         [
#             "twitch-dl",
#             "download",
#             f"{nro_video_para_baixar}"]
#     )
