#-*- coding: utf-8 -*-

# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

from .. import qt
from .more import LabelWordWrap, show_msg, get_icon
import datetime
from calculate.lib.datavars import DataVars

# _('The user should not be root')
class HelpWgt(qt.QWidget):
    def __init__(self, parent):
        super().__init__()

        clVars = DataVars()
        clVars.flIniFile()
        cur_year = str(datetime.date.today().year)
        copy_right = "&copy;"
        motto = 'Easy Linux from the Source.<br>'
        help_text = ('%s v%s. \n' %(parent.ClientObj.Name,
                parent.ClientObj.Version) + 
                _('Makes part of Calculate Utilities %s')%clVars.Get('cl_ver')
                + '<br>' + 
                _('Company') + ' Calculate %s 2007-%s' %(copy_right,cur_year))

        html_help = ("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0//EN' "
                  "'http://www.w3.org/TR/REC-html40/strict.dtd'>"
                  "<html><head><style type=text/css>"
                  "</style></head><body>" + help_text + "</body></html>")

        helpLabel = LabelWordWrap(html_help, self)
        helpLabel.setContentsMargins(10,10,10,5)
        company_name = _('Developer:') + " " +  _("Calculate company")
        company_site = 'http://www.calculate.ru'
        distr_name = _('Distribution website')
        distr_site = 'http://www.calculate-linux.org'
        linkLabel = LabelWordWrap(company_name + \
                "<br><a href='http://www.calculate.ru'>" + \
                company_site + "</a><br><br>" + distr_name+ \
                ": <br><a href='http://www.calculate-linux.org'>" + \
                distr_site + "</a>", self)

        linkLabel.setContentsMargins(10,5,10,5)
        linkLabel.setOpenExternalLinks(True)
        helpQuit = qt.QPushButton(_("Close"), self)
        helpQuit.setShortcut(qt.QKeySequence(qt.Qt.Key_Escape))
        helpQuit.setFixedWidth(100)

        self.image_lbl = qt.QLabel(self)

        filename = '/usr/share/icons/hicolor/scalable/apps/' \
                   'calculate-console.svg'
        ir = qt.QImageReader(filename)

        diff = ir.size().width() / 140.0
        w = ir.size().width() / diff
        h = ir.size().height() / diff
        if w > 2 * h:
            ir.setScaledSize(qt.QSize(1.7 * w, 1.7 * h))
        else:
            ir.setScaledSize(qt.QSize(w, h))
        img = ir.read()
        pm2 = qt.QPixmap().fromImage(img)

        self.image_lbl.setPixmap(pm2)

        layout = qt.QGridLayout(self)
        layout.setContentsMargins(24,10,24,10)
        layout.setAlignment(qt.Qt.AlignTop)

        layout.addWidget(self.image_lbl, 0,0,3,1)
        layout.addWidget(helpLabel,0,1)
        layout.addWidget(linkLabel,1,1)
        layout.addWidget(helpQuit,2,1, qt.Qt.AlignRight)
        self.setLayout(layout)
        helpQuit.clicked.connect(self.close)

#        self.setFixedSize(400 + x ,200)
        self.setFixedSize(self.sizeHint().width() + 50, \
                          self.sizeHint().height())
        self.setWindowTitle (_('Calculate Console '))
        help_icon = get_icon(
            '/usr/share/pixmaps/calculate-console-online.svg',
            "help-about")
        self.setWindowIcon (help_icon)

        self.move(parent.window().geometry().x() + \
                  parent.window().geometry().width() / 2 \
                  - self.size().width() / 2, \
                  parent.window().geometry().y() + \
                  parent.window().geometry().height() / 2 \
                  - self.size().height() / 2)

        # for clear memory after closed this window
        self.setAttribute(qt.Qt.WA_DeleteOnClose)

class HandBookWgt(HelpWgt):
    def __init__(self, parent, window):
        HelpWgt.__init__(self, parent)

# send report Bug in email
import smtplib, re
import email.utils
from email.mime.text import MIMEText

class BugWgt(qt.QWidget):
    def __init__(self, parent):
        super().__init__()
        name_lbl = qt.QLabel(_('Your name:'), self)
        self.name_edit = qt.QLineEdit(self)

        send_mail_lbl = qt.QLabel(_('Your email:') + ' *', self)
        send_mail_lbl.setToolTip(_('Please enter a valid email. ') + '\n' + \
                 _('If the email does not exist, you will receive no letter'))
        self.send_mail_edit = qt.QLineEdit(self)
        self.send_mail_edit.setToolTip(_('Please enter a valid email. ')+'\n'+\
                 _('If the email does not exist, you will receive no letter'))

        subject_lbl = qt.QLabel(_('Subject:'), self)
        self.subject_edit = qt.QLineEdit(self)

        message_lbl = qt.QLabel(_('Message:'), self)
        self.message_edit = qt.QTextEdit(self)

        Send_button = qt.QPushButton(_("Send a Bug"), self)
        Send_button.setShortcut(qt.QKeySequence(qt.Qt.Key_Return))
        Send_button.setMinimumWidth(Send_button.sizeHint().width())
        Send_button.clicked.connect(self.send_bug)

        Quit_button = qt.QPushButton(_("Close"), self)
        Quit_button.setShortcut(qt.QKeySequence(qt.Qt.Key_Escape))
        Quit_button.clicked.connect(self.close)

        layout = qt.QGridLayout(self)
        layout.setColumnStretch(0,0)
        layout.setColumnStretch(1,1)

        layout.addWidget(name_lbl, 0,0, qt.Qt.AlignRight)
        layout.addWidget(self.name_edit, 0, 1, 1, 2)        

        layout.addWidget(send_mail_lbl, 1,0, qt.Qt.AlignRight)
        layout.addWidget(self.send_mail_edit, 1, 1, 1, 2)

        layout.addWidget(subject_lbl, 2,0, qt.Qt.AlignRight)
        layout.addWidget(self.subject_edit, 2, 1, 1, 2)

        layout.addWidget(message_lbl, 3,0, qt.Qt.AlignRight | \
                                           qt.Qt.AlignTop)
        layout.addWidget(self.message_edit, 3,1, 2, 2)

        button_layout = qt.QHBoxLayout()
        button_layout.addWidget(Send_button)
        button_layout.addWidget(Quit_button)
        layout.addLayout(button_layout, 5, 1, 1, 2, qt.Qt.AlignRight)
        self.setLayout(layout)

        self.resize(350, 250)

        # Set title and icon
        self.setWindowTitle (_('Calculate Console '))
        bug_icons = ['tools-report-bug','system-help','help-browser']

        self.setWindowIcon(get_icon(*bug_icons))
        self.setWindowTitle(_("Report a Bug"))

        self.move(parent.window().geometry().x() +
                  parent.window().geometry().width() / 2
                  - self.size().width() / 2,
                  parent.window().geometry().y() +
                  parent.window().geometry().height() / 2
                  - self.size().height() / 2)   

        # for clear memory after closed this window
        self.setAttribute(qt.Qt.WA_DeleteOnClose)

    def set_message_text(self, text):
        self.message_edit.setText(text)

    def send_bug(self):
        name = self.name_edit.text()

        sender = self.send_mail_edit.text()
        mail_re = re.compile("^[a-zA-Z_0-9\.\-]{1,32}[\@]{1}[a-zA-Z_0-9]"+\
                             "{1,16}[\.]{1}[a-zA-Z]{1,3}$")
        if not mail_re.findall(sender):
            show_msg (_('Enter a valid email!'))
            return 1

        to_name = 'calculate bug report'
        receivers = 'mh@calculate.ru'
        subject = self.subject_edit.text()

        body = self.message_edit.toPlainText()
        try:
            body = body.encode('utf-8')
        except:
            body = str(body)

        # assemble the message
        performDebugging = False
        msg = MIMEText(body)
        msg.set_charset('utf-8')
        msg['To'] = email.utils.formataddr((to_name, receivers))
        msg['From'] = email.utils.formataddr((name, sender))
        msg['Subject'] = 'Bug Report: ' + subject

        server = smtplib.SMTP('mail')
        server.set_debuglevel(performDebugging)
        try:
            server.sendmail(sender, [receivers], msg.as_string())
            show_msg (_("Message sent!"))
            server.quit()
            self.close()
        except:
            show_msg (_("Sending error"))
            server.quit()
