#!/usr/bin/python2 -O
# -*- coding: utf-8 -*-`
# vim: set ts=4 sw=4 sts=4 et :
'''
alert - Displays a dialog message box contining text from a YAML configuration
        file

This file is part of Qubes+Whonix.
Copyright (C) 2014 - 2015 Jason Mehring <nrgaway@gmail.com>
License: GPL-2+
Authors: Jason Mehring

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import sys
import argparse
import locale
import yaml

from PyQt4 import QtGui

DEFAULT_LANG = 'en'


class Messages():
    filename = None
    data = None
    language = DEFAULT_LANG
    title = None
    icon = None
    message = None

    def __init__(self, section, filename):
        self.filename = filename

        language = locale.getdefaultlocale()[0].split('_')[0]
        if language:
            self.language = language

        try:
            stream = file(filename, 'r')
            data = yaml.load(stream)

            if section in data.keys():
                section = data[section]

                self.icon = section.get('icon', None)

                language = section.get(self.language, DEFAULT_LANG)

                self.title = language.get('title', None)
                self.message = language.get('message', None)

        except (IOError):
            pass
        except (yaml.scanner.ScannerError, yaml.parser.ParserError):
            pass


class WhonixMessageBox(QtGui.QMessageBox):
    '''
    '''
    def __init__(self, message):
        super(WhonixMessageBox, self).__init__()
        self.message = message
        self.initUI()

    def initUI(self):
        message = self.message

        if message.title:
            self.setWindowTitle(message.title)

        if message.icon:
            self.setIcon(getattr(QtGui.QMessageBox, message.icon))

        if message.message:
            self.setText(message.message)
            self.exec_()


def main():
    parser = argparse.ArgumentParser(description='Display a QT Message Box')

    parser.add_argument('section', help="Message section")
    parser.add_argument('filename', help="File including full path")

    args = parser.parse_args()

    if not args.filename and args.section:
        print parser.usage()
        sys.exit(1)

    app = QtGui.QApplication(sys.argv)

    message = Messages(args.section, args.filename)
    dialog = WhonixMessageBox(message)
    sys.exit()

if __name__ == "__main__":
    main()
