import requests
import os
import re
from datetime import datetime, timedelta
from dotenv import load_dotenv
from django.urls import reverse
from django.conf import settings

load_dotenv()


class Spotify():
    def __init__(self):
        self.token = None
        self.valid_until = None

    def redirect_uri(self):
        return settings.CURRENT_HOST + reverse('spotify-callback')

    def token_valid(self):
        if self.token and self.valid_until and (datetime.now() < self.valid_until):
            return True
        return False

    def get_token_json(self, grant_type, code=None, refresh_token=None):
        url = 'https://accounts.spotify.com/api/token'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + os.getenv('SPOTIFY_ENCODED_ID')
        }
        data = {
            'grant_type': grant_type
        }
        if code:
            data['code'] = code
        data['redirect_uri'] = self.redirect_uri()
        if refresh_token:
            data['refresh_token'] = refresh_token
        r = requests.post(url, headers=headers, data=data)
        return r.json()

    def get_system_token(self):
        if self.token_valid():
            return self.token
        data = self.get_token_json('client_credentials')
        self.token = data["access_token"]
        self.valid_until = datetime.now() + timedelta(seconds=data["expires_in"]-300)
        return self.token

    def get_user_token(self, code):
        data = self.get_token_json('authorization_code', code, redirect=True)
        print(data)
        return data
        return (data.get('access_token', None), data.get('refresh_token', None))

    def get_oauth_redirect(self):
        scopes = ['user-read-private', 'user-read-email']
        CLIENT_ID = 'bcc523219d1d4248a7e8892e809a5767' #TODO: delet.
        url = f'https://accounts.spotify.com/authorize?'
        url += f'client_id={CLIENT_ID}&'
        url += f'response_type=code&'
        url += f'scope={"%20".join(scopes)}&'
        url += f'redirect_uri={self.redirect_uri()}'
        print(url)
        return url

    def unshort(self, url):
        """Converts a spotify.link url into a normal spotify URL with ID"""
        r = requests.get(url, allow_redirects=False)
        r.raise_for_status()
        return r.headers["Location"]

    def get_song_info(self, spotify_id):
        token = self.get_system_token()
        url = 'https://api.spotify.com/v1/tracks/' + spotify_id
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        return r.json()

    def get_profile(self, access_token):
        url = 'https://api.spotify.com/v1/me'
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + access_token
        }
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        return r.json()

    def get_playlist_info(self, playlist_id):
        token = self.get_system_token()
        url = 'https://api.spotify.com/v1/playlists/' + playlist_id
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        return r.json()

spt = Spotify()