#-*- 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
import urllib.request as urllib2
from calculate.lib.utils.tools import Locker

from .more import show_msg, LabelWordWrap, get_ip_mac, get_sid, get_icon, dpivalue

def client_sid(sid, client, cert_id, lang):
    """ get number session from server and write this in file """
    new_sid = client.service.post_sid(sid, cert_id, lang)
    sid = str(new_sid[0][0])
    client.service.active_client(sid)
    server_host_name = client.server_host_name

    find_flag = False
    with Locker(fn=client.SID_LOCK):
        fs = open(client.SID_FILE, 'r')
        lines = fs.readlines()
        fs.close()

        fi = open(client.SID_FILE, 'w')
        for line in lines:
            word = line.split()
            if word:
                if word[0] == server_host_name:
                    find_flag = True
                    line = '%s %s\n' %(word[0], sid)
                fi.write(line)

        if not find_flag:
            fi = open(client.SID_FILE, 'a')
            fi.write('%s %s\n' %(server_host_name, sid))
            fi.close()
#    if new_sid[0][1] == 1:
    return [sid, new_sid[0][1]]

def client_post_cert (client, lang):
    """ send a certificate server for check """
    sid = get_sid(client)
    results = client.service.post_cert()
    if results[0][0] == -4:
        show_msg (_("Certificate not found in the server!"), _('Error'))
        raise Exception()
    sid, new_session = client_sid(sid, client, results[0][0], lang)
    if new_session:
        _print (_(" New session"))
    else: _print (_(" Old session"))
    _print (_(" Your session ID: %s") %sid)
    if results[0][0] == -3:
        _print (_("Certificate not sent!"))
    else:
        _print (_(" Your certifitate ID: %d") %(results[0][0]))
        try:
            if results[0][1] == -2:
                _print (_("Certificate expired"))
            elif results[0][1] > 0:
                _print (_("The certificate expires after %d days")%(results[0][1]))
        except:
            pass

class ViewSessionInfo (qt.QWidget):
    def __init__(self, parent, client, window):
        super().__init__()
        self.layout = qt.QGridLayout()

        sid = get_sid(client)
        try:
            results = client.service.post_cert()
        except urllib2.URLError:
            self.layout.addWidget(LabelWordWrap (_('Not connected!')))
            self.setLayout(self.layout)
            return 1

        ip, mac = get_ip_mac()

        if results[0][0] == -4:
            self.layout.addWidget(LabelWordWrap(_('Certificate not found in'
                        ' the server!'), self), 0,0,1,2)
            self.setLayout(self.layout)
            return 1

        sid = get_sid(client)
        self.layout.addWidget(LabelWordWrap(_('Your session ID: ')+str(sid),
                                            self), 4,0,1,2)

        if results[0][0] == -3:
            self.layout.addWidget(LabelWordWrap(_('Certificate not sent!'),
                                                self), 5,0,1,2)
        else:
            self.layout.addWidget(LabelWordWrap(_("Your certificate ID: ") \
                            + str(results[0][0]), self), 5,0,1,2)
            try:
                if results[0][1] == -2:
                    self.layout.addWidget(LabelWordWrap(_('Certificate '
                                'expired'), self), 6,0,1,2)
                elif results[0][1] > 0:
                    self.layout.addWidget(LabelWordWrap(_('The certificate '
                    'expires after %d days')%(results[0][1]), self), 6,0,1,2)
            except:
                pass
        self.layout.addWidget(LabelWordWrap(_('Your IP address: ') + ip,
                                            self), 7,0,1,2)
        self.layout.addWidget(LabelWordWrap(_('Your MAC address: ') + mac,
                                            self), 8,0,1,2)

        # Add clear cache Button
        self.clear_cache_button = qt.QPushButton \
                                    (_("Clear the session cache"), self)
        self.clear_cache_button.clicked.connect(self.clear_cache(client, sid))
        self.layout.addWidget(self.clear_cache_button, 9,0)

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

        self.layout.addWidget(Quit_button, 9, 1)
        Quit_button.clicked.connect(self.close)

        self.setFixedSize(dpivalue(260),100 + dpivalue(100))
        self.setLayout(self.layout)

        self.setWindowIcon(get_icon("document-edit-verify"))
        self.setWindowTitle(_('Session information'))

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

    def clear_cache(self, client, sid):
        def wrapper():
            try:
                res = client.service.clear_session_cache(sid)
            except Exception as e:
                show_msg(e, 'Error')
                return 1
            if res:
                show_msg(_('Error clearing the session cache'), parent = self)
            else:
                show_msg(_('Session cache cleared'), parent = self)
        return wrapper
