from psychopy.alerts import catalog
from psychopy import core
import sys

write_mode = 'w'

alertmsgFile = 'alertmsg.py'

try:
    fp = open(alertmsgFile, write_mode)
    fp.write('#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n')
    fp.write('# This file was generated by generateAlertmsg.py.\n')
    fp.write('# Following strings are used to localize alerts.\n')
    fp.write('# Rebuild this file if alert messages in *.yaml files'
             ' are modified.\n\n')
    fp.write('from psychopy.localization import _translate\n\n')
except Exception:
    # If hints.py could not be opend as a writable file, output to STDOUT.
    fp = sys.stdout
    fp.write('# Warning: could not open alertmsg.py. STDOUT is selected.')

for id in catalog.alert:
    if not isinstance(id, int) or id in (9998, 9999):
        continue
    
    fp.write('# Alert {}\n'.format(id))
    msg = catalog.alert[id]['msg'].replace(
        '\\', '\\\\').replace('"', '\\"')  # escape double quotation marks
    fp.write('_translate("{}")\n\n'.format(msg))

fp.close()

cmd = ['autopep8', alertmsgFile, '--in-place']
core.shellCall(cmd)
