import vkaudiotoken 
import requests
import re
_pattern = re.compile(r'/[a-zA-Z\d]{6,}(/.*?[a-zA-Z\d]+?)/index.m3u8()')


class ParseVK:
    def __init__(self, login, password):
        info = vkaudiotoken.get_vk_official_token(login, password)
        self.token  = info['token']
        self.user_agent = info['user_agent']
        self.userid = info['user_id']

    def to_mp3(self, url):
        return _pattern.sub(r'\1\2.mp3',url)

    def get_recomentation(self, count):
        sess = requests.session()
        sess.headers.update({'User-Agent': self.user_agent})

        q = sess.get(
            "https://api.vk.com/method/audio.getRecommendations",
            params=[('access_token', self.token),
                    ('user_id ', self.userid),
                    ('count', count),
                    ('v', '5.81')]
        ).json()

        list_a = []
        for x in q['response']['items']:
            temp = []
            artist = x['artist']
            temp.append(artist)
            title = x['title']
            temp.append(title)
            album = x['album']['title']
            temp.append(album)
            m3u8_url = x['url']
            url = self.to_mp3(m3u8_url)
            temp.append(url)

            list_a.append(temp)

        return list_a

        """
        for x in q['response']:
            print(x)
        
       
            temp = []
            artist = x['artist']
            temp.append(artist)
            title = x['title']
            temp.append(title)
            m3u8_url = x['url']
            url = self.to_mp3(m3u8_url)
            temp.append(url)

            list_a.append(temp)
            
        return list_a
        """

    def search(self, q, count):
        sess = requests.session()
        sess.headers.update({'User-Agent': self.user_agent})

        q = sess.get(
            "https://api.vk.com/method/audio.search",
            params=[('access_token', self.token),
                    ('q', q),
                    ('count', count),
                    ('v', '5.81')]
        ).json()

        list_a = []
        for x in q['response']['items']:
            temp = []
            artist = x['artist']
            temp.append(artist)
            title = x['title']
            temp.append(title)
            m3u8_url = x['url']
            url = self.to_mp3(m3u8_url)
            temp.append(url)

            list_a.append(temp)
            
        return list_a


