import os
import glob
import shutil
from tinytag import TinyTag

""" root = 'C:/'
copy_to = '/copy to/folder'
tag = TinyTag.get('C:/Users/jchap/OneDrive/Pictures/(VERYRAREBOYZ) (feat. $ki Mask The Slump God and Drugz).mp3')
print(tag.artist)
print('song duration: '+str(tag.duration))
 """

f = []
f=glob.glob('C:/Users/jchap/OneDrive/*.mp3')
print(f)

musicDirectory=[]
musicFiles =[]
# tag = TinyTag.get(f[0])
# print(tag.artist)

# for root, dirs, files in os.walk("C:/Users/jchap/OneDrive/"):
for root, dirs, files in os.walk("C:/"):
    for file in files:
        if file.endswith(".mp3"):
             musicFiles.append(file)
             musicDirectory.append(os.path.join(root, file))
             #print(os.path.join(root, file))

print('files'+str(musicFiles))
tag = TinyTag.get(musicDirectory[0])
print('Artist',tag.artist)
print('Album Artist',tag.albumartist)
print('Title',tag.title)
print('Biterate',tag.bitrate)

print('music directory'+str(musicDirectory))
print(len(musicDirectory))

currentDirectory =os.path.dirname(__file__)




with open(currentDirectory+'/The_Krabby_Patty Formula_.m3u', "r") as f:
    content_list = [word.strip() for word in f]

""" my_file = open(currentDirectory+'/The_Krabby_Patty Formula_.m3u', "r")
content_list = my_file. readlines() """

# print('playlist contents')
# print(content_list)

musicDirectory
musicWithoutDuplicates = []
duplicatesList = []
count =0
# check for tags equal to none

#musicDirectory =[x for x in musicDirectory j = TinyTag.get(x)  if x != 'wdg']


#remove tracks without albumn artist or title
for track in reversed(range(len(musicDirectory))):
    try:
        trackTag = TinyTag.get(musicDirectory[track])    
        if str(trackTag.albumartist)== 'None' or str(trackTag.title)=='None':
            print('albumArtist = none',musicDirectory[track]) 
            print('removing track and adding to log file')
            musicDirectory.remove(musicDirectory[track])
    except IndexError:
        break




#check for duplicates
for j in range(len(musicDirectory)):
    musicDtag = TinyTag.get(musicDirectory[j])
    duplicateL=[]
    duplicateLBiterate=[]
    for duplicate in range(len(musicDirectory)):
        
        duplicateTag = TinyTag.get(musicDirectory[duplicate])
        musicWithoutDuplicates.append(musicDirectory[j])

        if duplicateTag.albumartist == musicDtag.albumartist or duplicateTag.albumartist in musicDtag.albumartist:
            if duplicateTag.title == musicDtag.title or duplicateTag.title in musicDtag.title  :
                #check if last iteration
                if duplicate>=len(musicDirectory)-1:
                    print("found a duplicate!",musicDirectory[duplicate],duplicateTag.albumartist,duplicateTag.title)
                    
                    if len(duplicateLBiterate)==1:## did something here may need to change the conditional statement or add another 
                        print('biterate')
                        #[x for x in duplicateL if TinyTag.get(musicDirectory[x]).bitrate > musicDirectory[x]]
                        print("Current duplicate Bite rate", duplicateLBiterate)                                               
                        for x in range(len(duplicateL)):  
                            if TinyTag.get(duplicateL[x]).bitrate  == max(duplicateLBiterate):
                                #REMOVE ONE WITH THE BEST BITERATE
                                duplicateL.remove(duplicateL[x])
                                print('duplicate list',duplicateL)
                                #Add
                                duplicatesList = duplicatesList + duplicateL
                else:
                    print("found a duplicate!",musicDirectory[duplicate],duplicateTag.albumartist,duplicateTag.title)
                    duplicateL.append(musicDirectory[duplicate])
                    duplicateLBiterate.append(duplicateTag.bitrate)
print('dup ',duplicatesList)

#remove duplicates from list
for u in range(len(duplicatesList)):
    for i in range(len(musicDirectory)):
        if duplicatesList[u]==musicDirectory[i]:
            musicDirectory.remove(musicDirectory[i])
print('music ',musicDirectory)


#create playlist
newPlaylist = open("Test.m3u", "w")


#add file path to the respective track in the new playlist
for content in enumerate(content_list):
    # split strings into artist and title
    trackNumber=content[0]
    trackArray =str(content[1]).split('-')
    albumArtist= trackArray[0].strip()
    title=trackArray[1].strip()
    print('title:',title)
    print('albumArtist:',albumArtist)

    
    for trackDirectory in range(len(musicDirectory)):
        
        trackTag = TinyTag.get(musicDirectory[trackDirectory])
        
        if trackTag.albumartist == albumArtist or trackTag.albumartist in albumArtist:
            if trackTag.title == title or trackTag.title in title:
                newPlaylist.write(trackDirectory + " " + content)
                newPlaylist.close()
                try:
                    while True:
                        content.next()
                except StopIteration:
                    pass

                break
            else:
                print()
        else:
            print()
[((14, 2, 14, 44), 'glob.glob', 'glob.glob', ({(14, 12, 14, 43): '"""C:/Users/jchap/OneDrive/*.mp3"""'}, {}), "('C:/Users/jchap/OneDrive/*.mp3')", False, 'import glob\n'), ((23, 25, 23, 39), 'os.walk', 'os.walk', ({(23, 33, 23, 38): '"""C:/"""'}, {}), "('C:/')", False, 'import os\n'), ((31, 6, 31, 36), 'tinytag.TinyTag.get', 'TinyTag.get', ({(31, 18, 31, 35): 'musicDirectory[0]'}, {}), '(musicDirectory[0])', False, 'from tinytag import TinyTag\n'), ((40, 18, 40, 43), 'os.path.dirname', 'os.path.dirname', ({(40, 34, 40, 42): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((79, 16, 79, 46), 'tinytag.TinyTag.get', 'TinyTag.get', ({(79, 28, 79, 45): 'musicDirectory[j]'}, {}), '(musicDirectory[j])', False, 'from tinytag import TinyTag\n'), ((66, 19, 66, 53), 'tinytag.TinyTag.get', 'TinyTag.get', ({(66, 31, 66, 52): 'musicDirectory[track]'}, {}), '(musicDirectory[track])', False, 'from tinytag import TinyTag\n'), ((84, 23, 84, 61), 'tinytag.TinyTag.get', 'TinyTag.get', ({(84, 35, 84, 60): 'musicDirectory[duplicate]'}, {}), '(musicDirectory[duplicate])', False, 'from tinytag import TinyTag\n'), ((135, 19, 135, 62), 'tinytag.TinyTag.get', 'TinyTag.get', ({(135, 31, 135, 61): 'musicDirectory[trackDirectory]'}, {}), '(musicDirectory[trackDirectory])', False, 'from tinytag import TinyTag\n'), ((27, 35, 27, 59), 'os.path.join', 'os.path.join', ({(27, 48, 27, 52): 'root', (27, 54, 27, 58): 'file'}, {}), '(root, file)', False, 'import os\n'), ((98, 31, 98, 57), 'tinytag.TinyTag.get', 'TinyTag.get', ({(98, 43, 98, 56): 'duplicateL[x]'}, {}), '(duplicateL[x])', False, 'from tinytag import TinyTag\n')]