def generate(inputStr,
             deckName,
             hires=False,
             reprint=False,
             nocache=False,
             imgurId=None,
             dropboxToken=None,
             output='',
             basicSet=None):

    try:
        if not checkIntegrations(hires, imgurId, dropboxToken):
            return

        decklist = getDecklist(inputStr)
        if decklist == None:
            return

        print('Processing decklist')
        ttsJson = converter.convertDecklistToJSON(decklist, deckName, hires,
                                                  reprint, nocache, imgurId,
                                                  dropboxToken, output,
                                                  basicSet)
        ttsJsonFilename = os.path.join(output, deckName + '.json')
        with open(ttsJsonFilename, 'w', encoding='utf8') as outfile:
            json.dump(ttsJson, outfile, indent=2)
        queue.sendMessage({'type': 'done'})
        print('All done')
    except:
        # Handle random uncaught exceptions "gracefully"
        errorMessage = 'Error: ' + sys.exc_info()[0].__name__
        queue.sendMessage({'type': 'error', 'text': errorMessage})
        print(errorMessage)
        traceback.print_tb(sys.exec_info()[2])
def generateDraft(setName,
                  packCount,
                  hires=False,
                  imgurId=None,
                  dropboxToken=None,
                  output=''):
    try:
        if not checkIntegrations(hires, imgurId, dropboxToken):
            return

        ttsJson = converter.convertSetToDraftJSON(setname, packCount, hires,
                                                  imgurId, dropboxToken,
                                                  output)
        ttsJsonFilename = os.path.join(
            output,
            setName + '-draft-' + strftime("%Y%m%d%H%M%S", gmtime()) + '.json')
        with open(ttsJsonFilename, 'w', encoding='utf8') as outfile:
            json.dump(ttsJson, outfile, indent=2)
        queue.sendMessage({'type': 'done'})
        print('All done')
    except:
        # Handle random uncaught exceptions "gracefully"
        errorMessage = 'Error: ' + sys.exc_info()[0].__name__
        queue.sendMessage({'type': 'error', 'text': errorMessage})
        print(errorMessage)
        traceback.print_tb(sys.exec_info()[2])
def checkDropbox(dropboxToken):
    try:
        dbx = dropbox.Dropbox(dropboxToken)
        dbx.users_get_current_account()
    except:
        print('Problem with dropbox integration')
        queue.sendMessage({
            'type': 'error',
            'text': 'Problem with Dropbox integration'
        })
        return False
    return True
def checkImgur(imgurId):
    try:
        client = ImgurClient(imgurId, '')
    except ImgurClientError:
        print('Imgur client information incorrect')
        queue.sendMessage({
            'type':
            'error',
            'text':
            'Imgur client ID wrong. See README for details.'
        })
        return False
    return True
def getDecklist(inputStr):
    """
    Finds the decklist list from a given input string. If the string is an URL to deckbox.org or tappedout.net,
    the function will try to download the decklist. Otherwise, the string is interpreted to be a filename.
    """
    if re.match('http', inputStr):
        print('Generating from URL ' + inputStr)
        if re.search('deckbox.org', inputStr):
            # Deckbox.org URL
            response = requests.get(inputStr + '/export')
            deckboxHtml = response.text
            bodyStart = re.search('<body>', deckboxHtml).end()
            bodyEnd = re.search('</body>', deckboxHtml).start()
            deckboxHtmlBody = deckboxHtml[bodyStart:bodyEnd]
            decklist = deckboxHtmlBody.replace('<p>', '').replace(
                '</p>', '').replace('<strong>', '').replace('</strong>',
                                                            '').split('<br/>')
        elif re.search('tappedout.net', inputStr):
            #Tappedout URL
            if inputStr.find('?') > 0:
                # We got some parameters here, let's get rid of them.
                inputStr = inputStr[:inputStr.find('?')]
            response = requests.get(inputStr + '?fmt=txt')
            decklist = response.text.split('\n')
        else:
            print(
                'Input URL must be to either to https://deckbox.org or https://tappedout.net.'
            )
            queue.sendMessage({
                'type':
                'error',
                'text':
                'Input URL must be either to https://deckbox.org or https://tappedout.net'
            })
            return None
        del response
        return decklist
    else:
        print('Generating from file ' + inputStr)
        try:
            with open(inputStr, encoding='utf8') as decklistfile:
                decklist = decklistfile.readlines()
            return decklist
        except FileNotFoundError:
            print('File ' + inputStr + ' not found!')
            queue.sendMessage({
                'type': 'error',
                'text': 'File ' + inputStr + ' not found!'
            })
            return None
def checkMontage():
    try:
        returnVal = subprocess.call(['montage', '--version'])
        if returnVal == 0:
            images.setMontagePath('montage')
            return True
    except FileNotFoundError:
        pass

    #Global montage not found, let's try to find the bundled version.

    try:
        montagePath = os.path.join('imagemagick', 'montage')
        returnVal = subprocess.call([montagePath, '--version'])
        if returnVal == 0:
            images.setMontagePath(montagePath)
            return True
    except FileNotFoundError:
        pass

    print('Imagemagick not found!')
    queue.sendMessage({'type': 'error', 'text': 'Imagemagick not found!'})
    return False
def getDecklist(inputStr):
    """
    Finds the decklist list from a given input string. If the string is an URL to deckbox.org or tappedout.net,
    the function will try to download the decklist. Otherwise, the string is interpreted to be a filename.
    """
    if re.match('http', inputStr):
        print('Generating from URL ' + inputStr)
        if re.search('deckbox.org', inputStr):
            # Deckbox.org URL
            response = requests.get(inputStr + '/export')
            deckboxHtml = response.text
            bodyStart = re.search('<body>', deckboxHtml).end()
            bodyEnd = re.search('</body>', deckboxHtml).start()
            deckboxHtmlBody = deckboxHtml[bodyStart:bodyEnd]
            decklist = deckboxHtmlBody.replace('<p>', '').replace(
                '</p>', '').replace('<strong>', '').replace('</strong>',
                                                            '').split('<br/>')
        elif re.search('tappedout.net', inputStr):
            #Tappedout URL
            if inputStr.find('?') > 0:
                # We got some parameters here, let's get rid of them.
                inputStr = inputStr[:inputStr.find('?')]
            response = requests.get(inputStr + '?fmt=txt')
            decklist = response.text.split('\n')
        elif re.search('scryfall', inputStr):
            key = inputStr.split('/')[-1]
            response = requests.get(
                f'https://api.scryfall.com/decks/{key}/export/text')
            decklist = [line for line in response.text.split('\r\n')]
        elif re.search('archidekt', inputStr):
            key = inputStr.split('/')[-1].split('#')[0]
            response = requests.get(
                f'https://archidekt.com/api/decks/{key}/small/')
            deckObj = json.loads(response.text)
            cards = deckObj['cards']
            decklists = {}
            for card in cards:
                category = card['category'].lower() if card['category'].lower(
                ) in ['commander', 'sideboard'] else ''
                cardName = f"{card['quantity']} {card['card']['oracleCard']['name']}"
                if category not in decklists:
                    decklists[category] = [cardName]
                else:
                    decklists[category].append(cardName)
            decklist = []
            for category in decklists:
                if category:
                    decklist.append(f'//{category}')
                for card in decklists[category]:
                    decklist.append(card)
        else:
            print(
                'Input URL must be to either to https://deckbox.org or https://tappedout.net.'
            )
            queue.sendMessage({
                'type':
                'error',
                'text':
                'Input URL must be either to https://deckbox.org or https://tappedout.net'
            })
            return None
        del response
        return decklist
    else:
        print('Generating from file ' + inputStr)
        try:
            with open(inputStr, encoding='utf8') as decklistfile:
                decklist = decklistfile.readlines()
            return decklist
        except FileNotFoundError:
            print('File ' + inputStr + ' not found!')
            queue.sendMessage({
                'type': 'error',
                'text': 'File ' + inputStr + ' not found!'
            })
            return None