from alive_progress import alive_bar
import sys, time
import discogs_client
from discogs_client.exceptions import HTTPError
import sqlite3
from sqlite3 import Error
sys.path.insert(1, 'j:\\Spotty\secrets_and_database')

class date_check:
    def __init__(self):
        self.consumer_key = 'JJCOegYnRLCLRejtcZbo'
        self.consumer_secret = 'UFlGrCViqSkoBNfRTGZyUfmpTGNbFbMM'
        self.user_agent = 'discogs_date_checker1.0'
        self.d = ""
        self.trkdate_list = []
        self.database = r"j:\Spotty\secrets_and_database\\Enormous Feed2.db"
        #self.database = r"j:\Spotty\secrets_and_database\\Endless Feed2.db"

    def do_the_stuff(self):
        self.authorise_discogs()
        self.check_release_date()

    def create_connection(self, db_file):  # NOTE Connect to the database
        conn = None
        conn = sqlite3.connect(db_file)
        return conn

    def authorise_discogs(self):
        # instantiate our discogs_client object.
        self.d = discogs_client.Client(self.user_agent)
        # prepare the client with our API consumer data.
        self.d.set_consumer_key(self.consumer_key, self.consumer_secret)
        self.token, self.secret, self.url = self.d.get_authorize_url()
        print(' == Request Token == ')
        print(f'    * oauth_token        = {self.token}')
        print(f'    * oauth_token_secret = {self.secret}')
        print()
        print(f'Please browse to the following URL {self.url}')
        accepted = 'n'
        while accepted.lower() == 'n':
            print
            accepted = input(f'Have you authorized me at {self.url} [y/n] :')
        oauth_verifier = input('Verification code : ')
        try:
            access_token, access_secret = self.d.get_access_token(
                oauth_verifier)
        except HTTPError:
            print('Unable to authenticate.')
            sys.exit(1)
        # fetch the identity object for the current logged in user.
        self.user = self.d.identity()
        print
        print(' == User ==')
        print(f'    * username           = {self.user.username}')
        print(f'    * name               = {self.user.name}')
        print(' == Access Token ==')
        print(f'    * oauth_token        = {access_token}')
        print(f'    * oauth_token_secret = {access_secret}')
        print(' Authentication complete. Future requests will be signed with the above tokens.')

    def check_release_date(self):
        conn = self.create_connection(self.database)
        cur = conn.cursor()
        cur.execute("SELECT COUNT (*) FROM Release_Date WHERE VERIFIED = 0 AND FMDate = '999'")
        self.total_records = int(cur.fetchone()[0])
        nextrec = 0
        cur = conn.cursor()
        #cur.execute("SELECT * FROM Release_Date WHERE VERIFIED = 0 ORDER BY ALBUM_NAME ASC")
        cur.execute("SELECT * FROM Release_Date WHERE VERIFIED = 0 AND FMDate = '999' ORDER BY ALBUM_NAME ASC")
        #cur.execute("SELECT * FROM Artist_Genre ORDER BY ARTIST_NAME ASC")
        rows = cur.fetchall()
        for row in rows:
            print("Working on Item " + str(nextrec) + " of " + str(self.total_records), end='\r')
            print()
            #time.sleep(5)
            #data_rec = 0
            self.orig_year = 9999
            self.duri = row[0]
            self.dtrack_name = row[2]
            self.dartist_name = row[3]
            self.dalbum_name = row[4]
            self.verified = row[7]
            #results = self.d.search(str(self.dartist_name), type='release', artist=str(self.dartist_name))
            results = self.d.search(str(self.dalbum_name), artist=str(self.dartist_name), type='release')
            #results = self.d.search(str(self.dtrack_name), type='release', artist=str(self.dartist_name))
            nextrec +=1
            for release in results:
                #print()
                time.sleep(0.5)
                
                self.trk_name = (f'\tTitle\t: {release.title}')
                
                print(self.dalbum_name + " - " + self.dartist_name + " - " + self.trk_name + " - " + self.dtrack_name)
                #print(self.trk_name)
                if self.dalbum_name.title() in self.trk_name.title():
                    try:
                        self.this_year = int((f'\tYear\t: {release.year}')[-4:])
                        if self.this_year < self.orig_year:
                            self.orig_year = self.this_year
                        continue
                    except:
                        continue
            if int(self.verified) == 0:
                self.update_release_date()
            else:
                continue

    def update_release_date(self):
        conn2 = self.create_connection(self.database)
        cur2 = conn2.cursor()
        try:
            if "'" in self.dalbum_name:
                self.dalbum_name = self.dalbum_name.replace("'", "''")
            cur2.execute("UPDATE Release_Date SET DISCOG_DATE = '" + str(self.orig_year) + "' WHERE ALBUM_NAME = '" + self.dalbum_name + "'")
            conn2.commit()
            if self.orig_year == 9999:
                cur2.execute("UPDATE OR IGNORE Release_Date SET VERIFIED = 9999 WHERE ALBUM_NAME = '" + self.dalbum_name + "'")
                conn2.commit()
            else:
                cur2.execute("UPDATE OR IGNORE Release_Date SET VERIFIED = 1 WHERE ALBUM_NAME = '" + self.dalbum_name + "'")
                conn2.commit()
        except Error as e5:
            print("check_artist_genre_table")
            print(e5)
            return

a = date_check()
a.do_the_stuff()
