# Path: shmaplib/adobe.py
# class AdobeDocsParser(object):
#     """This parser scrapes shortcuts and contexts from an adobe shortcuts documentation html file, such as:
#     http://helpx.adobe.com/en/photoshop/using/default-keyboard-shortcuts.html
# 
#     It assumes the main relevant data is contained in a wrapper div: <div class="parsys main-pars">...</div>
#     From the contents of this div, it can extract shortcut contexts, shortcut names and keys for Windows and MacOS
#     """
# 
#     def __init__(self, app_name):
#         super(AdobeDocsParser, self).__init__()
#         self.idata = IntermediateShortcutData(app_name)
# 
#     @staticmethod
#     def _clean_text(text):
#         text = text.replace(u'\n', u' ').strip(u' ').replace(u'\xa0', u' ')
#         # Remove stuff within braces
#         text = re.sub("([\(]).*?([\)])", "", text)
#         # Remove meta-data tags
#         text = text.replace(u'†', u'').replace(u'‡', u'').strip(u'*')
# 
#         return text.strip(u' ')
# 
#     def parse(self, source_file_path):
#         if not os.path.exists(source_file_path):
#             log.error("Source file '%s' does not exist", source_file_path)
#             return
# 
#         # Use BeautifulSoup to parse the html document
#         doc = BeautifulSoup(_get_file_contents(source_file_path))
#         main_wrapper_div = doc.find("div", class_="parsys main-pars")
#         if main_wrapper_div is None:
#             main_wrapper_div = doc.find("div", id="main")
#         sections = main_wrapper_div.find_all("div", class_="parbase")
# 
#         # Iterate sections (headers are contexts, tables contain the shortcuts)
#         context_name = None
#         for section in sections:
#             # This section is a header, the only relevant information here is the context
#             if 'header' in section['class']:
#                 h2 = section.find('h2')
#                 context_name = str(h2.contents[0]).replace('\n', ' ').strip(' ')
#                 log.debug('Scanning context: "%s"', context_name)
# 
#             # This is a section containing the shortcuts table
#             elif 'table' in section['class']:
#                 rows = section.find('tbody').find_all('tr')
# 
#                 for row in rows:
#                     cols = row.find_all("td")
#                     if len(cols) != 3:
#                         continue
# 
#                     shortcut_name = self._clean_text(cols[0].get_text())
#                     keys_win = self._clean_text(cols[1].get_text())
#                     keys_mac = self._clean_text(cols[2].get_text())
# 
#                     self.idata.add_shortcut(context_name, shortcut_name, keys_win, keys_mac)
#                     log.debug('...found shortcut "%s"', shortcut_name)
# 
#         return self.idata


import sys
import os
import glob
import logging
import argparse
import re
import shmaplib
from shmaplib.adobe import AdobeDocsParser

# Import common scripts
CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, CWD)
sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..')))

# Import common shortcut mapper library
log = shmaplib.setuplog(os.path.join(CWD, 'output.log'))


def main():
    parser = argparse.ArgumentParser(description="Converts Illustrator's raw files to an intermediate format.")
    parser.add_argument('-v', '--verbose', action='store_true', required=False, help="Verbose output")
    parser.add_argument('-o', '--output', required=True, help="Output filepath")
    parser.add_argument('source', help="Source: HTML file containing shortcuts saved directly from adobe's online documentation (/raw folder)")

    args = parser.parse_args()
    args.source = os.path.abspath(args.source)
    args.output = os.path.abspath(args.output)

    if not os.path.exists(args.source):
        print("Error: the input source file doesn't exist.")
        return

    # Verbosity setting on log
    log.setLevel(logging.INFO)
    if args.verbose:
        log.setLevel(logging.DEBUG)

    # Parse the docs html

# Path: shmaplib/adobe.py
# class AdobeDocsParser(object):
#     """This parser scrapes shortcuts and contexts from an adobe shortcuts documentation html file, such as:
#     http://helpx.adobe.com/en/photoshop/using/default-keyboard-shortcuts.html
# 
#     It assumes the main relevant data is contained in a wrapper div: <div class="parsys main-pars">...</div>
#     From the contents of this div, it can extract shortcut contexts, shortcut names and keys for Windows and MacOS
#     """
# 
#     def __init__(self, app_name):
#         super(AdobeDocsParser, self).__init__()
#         self.idata = IntermediateShortcutData(app_name)
# 
#     @staticmethod
#     def _clean_text(text):
#         text = text.replace(u'\n', u' ').strip(u' ').replace(u'\xa0', u' ')
#         # Remove stuff within braces
#         text = re.sub("([\(]).*?([\)])", "", text)
#         # Remove meta-data tags
#         text = text.replace(u'†', u'').replace(u'‡', u'').strip(u'*')
# 
#         return text.strip(u' ')
# 
#     def parse(self, source_file_path):
#         if not os.path.exists(source_file_path):
#             log.error("Source file '%s' does not exist", source_file_path)
#             return
# 
#         # Use BeautifulSoup to parse the html document
#         doc = BeautifulSoup(_get_file_contents(source_file_path))
#         main_wrapper_div = doc.find("div", class_="parsys main-pars")
#         if main_wrapper_div is None:
#             main_wrapper_div = doc.find("div", id="main")
#         sections = main_wrapper_div.find_all("div", class_="parbase")
# 
#         # Iterate sections (headers are contexts, tables contain the shortcuts)
#         context_name = None
#         for section in sections:
#             # This section is a header, the only relevant information here is the context
#             if 'header' in section['class']:
#                 h2 = section.find('h2')
#                 context_name = str(h2.contents[0]).replace('\n', ' ').strip(' ')
#                 log.debug('Scanning context: "%s"', context_name)
# 
#             # This is a section containing the shortcuts table
#             elif 'table' in section['class']:
#                 rows = section.find('tbody').find_all('tr')
# 
#                 for row in rows:
#                     cols = row.find_all("td")
#                     if len(cols) != 3:
#                         continue
# 
#                     shortcut_name = self._clean_text(cols[0].get_text())
#                     keys_win = self._clean_text(cols[1].get_text())
#                     keys_mac = self._clean_text(cols[2].get_text())
# 
#                     self.idata.add_shortcut(context_name, shortcut_name, keys_win, keys_mac)
#                     log.debug('...found shortcut "%s"', shortcut_name)
# 
#         return self.idata


# Path: sources/adobe-illustrator/raw_to_intermediate.py
import sys
import os
import glob
import logging
import argparse
import re
import shmaplib
from shmaplib.adobe import AdobeDocsParser


# Import common scripts
CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, CWD)
sys.path.insert(0, os.path.normpath(os.path.join(CWD, '..', '..')))

# Import common shortcut mapper library
log = shmaplib.setuplog(os.path.join(CWD, 'output.log'))


def main():
    parser = argparse.ArgumentParser(description="Converts Illustrator's raw files to an intermediate format.")
    parser.add_argument('-v', '--verbose', action='store_true', required=False, help="Verbose output")
    parser.add_argument('-o', '--output', required=True, help="Output filepath")
    parser.add_argument('source', help="Source: HTML file containing shortcuts saved directly from adobe's online documentation (/raw folder)")

    args = parser.parse_args()
    args.source = os.path.abspath(args.source)
    args.output = os.path.abspath(args.output)

    if not os.path.exists(args.source):
        print("Error: the input source file doesn't exist.")
        return

    # Verbosity setting on log
    log.setLevel(logging.INFO)
    if args.verbose:
        log.setLevel(logging.DEBUG)

    # Parse the docs html

    docs_idata = AdobeDocsParser("Adobe Illustrator").parse(args.source)