from browser import document, aio, alert, window
from javascript import JSON

from base import BlockBase, Menu
import domtools
import blocks
import db_blocks
import api
import annotate
import crypto

#################################################################
# re-init tools for loading new page

def init_page_tools():
    document['searchresults'].parent.open = False # when new page loaded, hide old search


#################################################################
# app initialization

async def start_conrad(jwtUIID='get-jwt', fileID='jwt-file', passwordID='jwt-password',
                       windowName='ConradMain'):
    window.name = windowName
    data = await get_valid_login(fileID, passwordID)
    jwtkey = data['jwtkey']
    page = data.get('page', 'da0a2f81-a1e6-4707-998d-6f06827091da')
    # localhost dev server
    #dataLoader = DataLoader(jwtkey)
    # production server
    BlockBase.dataLoader = api.DataLoader(jwtkey, url='https://api.blindspots.institute/')
    BlockBase.dataLoader.init_page_tools = init_page_tools
    BlockBase.dataLoader.load_page(page)
    annotate.init_annotation_tool() # load the annotation prototype
    document[jwtUIID].style.display = 'none'
    domtools.add_rescaling(document['erdiagram-prototype'])
    chooser = db_blocks.create_modal_chooser('ModalChooser')
    db_blocks.RelationCellNode.chooser = chooser
    chooser = db_blocks.create_modal_chooser('SchemaChooser')
    db_blocks.RowBlockNode.chooser = chooser
    chooser = db_blocks.create_modal_chooser('TableViewChooser')
    db_blocks.ViewBlockNode.chooser = chooser
    chooser = db_blocks.create_modal_chooser('OwnerChooser')
    blocks.PageBlockNode.ownerChooser = chooser


async def get_valid_login(fileID, passwordID):
    'allow multiple login attempts using specified DOM elements for password and file'
    while True:
        try:
            jwtreader = domtools.LocalFileUI(fileID)
            s = await jwtreader.get_text()
            upassword = document[passwordID].value
            return await decrypt_jwt(s, upassword)
        except:
            alert('Invalid password or JWT file.  Please try again.')


async def decrypt_jwt(json64, upassword):
    'json64 must be JSON dict with keys ciphertext, tag, nonce, salt with base64 values'
    d64 = JSON.parse(json64)
    plaintext = (await crypto.decrypt_base64(upassword, **d64))[0]
    return JSON.parse(plaintext)


# initialize menus
BlockBase._menuIndex.update(
  {
    'addBlockMenu': Menu('addBlockMenu', ('Text', 'List', 'To Do', 'Quote',
                                          'Callout', 'Toggle', 'URL', 'Image',
                                          'Equation', 'Code', 'Heading', 'Subheading', 'Subheading 3',
                                          'New DB View',
                                          'PDF document', 'File', 'Audio File'),
                         ('TextBlock', 'ListBlock', 'ToDoBlock', 'QuoteBlock',
                          'CalloutBlock', 'ToggleBlock', 'LinkBlock', 'ImageBlock',
                          'MathBlock', 'CodeBlock', 'H1Block', 'H2Block', 'H3Block',
                          'newView',
                          'PdfBlock', 'FileBlock', 'AudioBlock')),
    'editBlockMenu': Menu('editBlockMenu', ('Cut', 'Paste', 'Delete', ),
                          ('cut_block', 'paste_block', 'delete_confirm', )),
    'xrefMenu': Menu('xrefMenu', ('Open', 'Unlink'), ('open', 'unlink')),
    'relationMenu': Menu('relationMenu', ('Link', 'New'), ('link', 'new')),
    'addXRefMenu': Menu('addXRefMenu', ('Link Existing Block', 'Link New Block',),
                        ('link', 'create',)),
    'formatToolbar': Menu('formatToolbar', ('<b>B</b>', '<i>It</i>', '<code>&lt;&gt;</code>',
                                            '&#x2211;', 'Annotate'),
                          ('bold', 'italic', 'code', 'equation', 'annotate'), 'ButtonTemplate',
                          withTitle=True),
    'editRowMenu': Menu('editRowMenu', ('Open as Page', 'Delete',),
                          ('open_as_page', 'delete_confirm',)),
    'addRowMenu': Menu('addRowMenu', ('Row', ),
                          ('RowBlock', )),
    'editHeaderMenu': Menu('editHeaderMenu', ('Insert Column', 'Hide Column',),
                          ('start_column', 'hide_column',)),
    'editPropertyMenu': Menu('editPropertyMenu', ('Rename', 'Delete',),
                          ('rename_property', 'delete_confirm',)),
    'addFilterMenu': Menu('addFilterMenu'),
    'editFilterMenu': Menu('editFilterMenu', ('Delete',), ('delete_confirm',)),
    'showColumnMenu': Menu('showColumnMenu'),
  }
)

aio.run(start_conrad())

