def new_template_note(guid):
    """Copies the note specified by the GUID in the URL

    redirects the user to open the note in their client"""

    # Check to see the user has logged in
    if "access_token" in session.keys():
        # Setup Evernote Client
        client = EvernoteClient(token=session["access_token"], sandbox=sandbox)
        user_store = client.get_user_store()
        business_store = client.get_business_note_store()

        auth_result = user_store.authenticateToBusiness()
        business_shard_id = auth_result.user.shardId
        business_user_id = auth_result.user.id
        business_token = auth_result.authenticationToken

        # Construct the evernote Link to the newly copied note
        in_app_link = "evernote:///view/%s/%s/%s/%s/" % (
            business_user_id,
            business_shard_id,
            guid,
            guid
        )

        # Redirect the user to the note (opens in Evernote client)
        return redirect(in_app_link)
    else:
        # If the user is not logged in redirect them to do so
        return redirect(url_for("main"))
print "Successfully created a new note with GUID: %s\n" % created_note.guid


# Evernote Business
# To learn more about Evernote Business see https://evernote.com/business
# For Evernote Business documentation see
# https://dev.evernote.com/doc/articles/business.php

# Check to see if the user is a part of a Evernote Business account
if user.accounting.businessId:
    # we're part of a business
    print "You have Evernote Business!"
    print "Business Name: %s\n" % user.accounting.businessName

    business_store = client.get_business_note_store()

    # List all of the notebooks in the business' account
    joined_b_ntbks = business_store.listNotebooks()
    joined_b_ntbk_guids = []
    print "Found", len(joined_b_notebooks), "joined business notebooks:"
    for business_notebook in joined_b_ntbks:
        print "  * ", business_notebook.name
        joined_b_ntbk_guids.append(business_notebook.guid)
    print ""

    # Get a list of accessible business notebooks
    accessible_b_ntbks = business_store.listAccessibleBusinessNotebooks()

    # Infer the list of unjoin business notebooks
    unjoined_b_ntbks = list(set(accessible_b_ntbks)-set(joined_b_ntbks))
def main():
    """Presents the user with notes tagged as templates

    If there are no notes tagged "template" or "Template" 4 example
    notes are created. If the user is not logged in: a splash page with
    the option to authorize the appliction is presented. Utilizes
    access tokenk stored in the session.
    """

    # Check to see the user has logged in
    if "access_token" in session.keys():
        try:
            # Setup Evernote client
            client = EvernoteClient(
                token=session["access_token"],
                sandbox=sandbox
            )
            user_store = client.get_user_store()
            note_store = client.get_note_store()
        except Errors.EDAMSystemException:
            # If the user authentication token fails to work
            # prompt them to reautenticate
            error_message = "Your session is no longer valid.  \
            Please click here <a href=\'/clear'>click here</a> \
            to reset and login again."
            return render_template("error.html", error_message=error_message)

        # If the user is not a part of the business, tell the user
        user = user_store.getUser()
        if not user.accounting.businessId:
            error_message = "This account is not a part of a business. \
            Please click here <a href=\'/clear'>click here</a> to reset \
            and try another account."
            return render_template("error.html", error_message=error_message)
        else:
            business_store = client.get_business_note_store()

        # Setup search
        notebook_filter = NoteStoreTypes.NoteFilter()
        result_spec = NoteStoreTypes.NotesMetadataResultSpec(includeTitle=True)

        # Start seraching for notes in the last day if less than 5
        # results increase to 10, 100, etc. until more than 5 are found
        # or the number results between iterations are the same
        search_results_len = None
        while search_results_len < 10:
            # Setup counter
            try:
                counter += 1
            except NameError:
                counter = 0

            # Define number of pervious days to search:
            days_pervious_to_search = str(int(math.pow(10, counter)))
            # Define search grammer
            # https://dev.evernote.com/doc/articles/search_grammar.php
            notebook_filter.words = "created:day-%s updated:day-%s" % \
                (days_pervious_to_search, days_pervious_to_search)

            # Execute search method call
            search_results = business_store.findNotesMetadata(
                notebook_filter,
                0,
                40000,
                result_spec
            )

            # Break if you get the same number of results for a order
            # of magnitude increase in the number of days (assume that
            # is the total number of search results present)
            if len(search_results.notes) == search_results_len
            and search_results_len != 0:
                break

            # If you search the last 10,000 days and there are not
            # business notes assume there are no business notes and
            # inform the user
            if counter == 4 and search_results_len == 0:
                error_message = "This account has no business notes! \
                Please click please add and sync some business notes \
                and refresh the page."
                return render_template(
                    "error.html",
                    error_message=error_message
                )

            search_results_len = len(search_results.notes)

        notes_metadata = search_results.notes

        auth_result = user_store.authenticateToBusiness()
        business_shard_id = auth_result.user.shardId
        business_user_id = auth_result.user.id
        business_token = auth_result.authenticationToken

        # Return the list of recently created and edited business notes
        # and their views and display them (with links) to the user
        for note in notes_metadata:
            # Construct a link to the template note with the form
            # evernote:///view/[userId]/[shardId]/[noteGuid]/[noteGuid]
            template_link = "evernote:///view/%s/%s/%s/%s/" % \
                (business_user_id, business_shard_id, note.guid, note.guid)

            # Construct a URL that allows the user to create a new note
            # based on the template
            in_app_link = "note/template/%s" % note.guid

            # Get the thumnail for each note
            thumbnail_url = "%s/shard/%s/thm/note/%s.jpg" % \
                (EN_URL, business_shard_id, note.guid)
            r = requests.post(thumbnail_url, data={"auth": business_token})

            # Base64 encode the image data to return with the page
            # this is to get avoid exposing the business token in
            # plain HTML on the page (which is requried to retrive
            # the image)
            image_data = "data:%s;base64,%s" % (
                r.headers['Content-Type'],
                str(base64.b64encode(r.content).decode("utf-8"))
            )

            # Wrap all this data in a dictionary and put it in a list
            try:
                content_list.append(
                    {"image": image_data,
                        "in_app_link": in_app_link,
                        "title": str(note.title).decode('utf-8')}
                )
            except NameError:
                content_list = [{
                	"image": image_data,
                    "in_app_link": in_app_link,
                    "title": str(note.title).decode('utf-8')
                }]

        # Render the template with the data we just retrivied
        return render_template(
            'index.html',
            templates=content_list,
            num_of_notes=days_pervious_to_search
        )