# -*- 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.
import os

import sys
from calculate.lib.utils.files import readLinesFile, readFile, writeFile
from calculate.lib.utils.tools import Locker

_ = lambda x: x
from calculate.lib.cl_lang import setLocalTranslate

setLocalTranslate('cl_console3', sys.modules[__name__])


def sid_inf(client, sid):
    """ get information about selected session """
    red = '\033[31m * \033[0m'
    green = '\033[32m * \033[0m'
    s = client.service.sid_info(sid)
    if s[0][0] == "-1":
        print red + _("Session non registered on the server!")
        return -1
    if s[0][0] == "-2":
        print red + _("Failed to obtain certificate data!")
        return -2
    if s[0][0] == "Permission denied":
        print red + _("%s: permission denied") % s[0][1]
        return -3

    print _('Session information: ')
    print green + _(u"ID: %s") % sid
    print green + _(u"Certificate number: %s") % s[0][0]
    print green + _(u"Certificate issued: %s") % s[0][1].partition(".")[0]
    print green + "IP: %s" % s[0][2]
    print green + "MAC: %s\n" % s[0][3]
    return 0


def client_session_info(client, sid=None):
    """ select session for get information """
    try:
        select_sid = sid if sid else client.sid
        sid_inf(client, select_sid)
    except Exception, e:
        if type(e.message) == tuple and len(e.message) == 2 \
                and e.message[1] == 'Forbidden':
            print _("Access forbidden!")
        else:
            print e
        return 1


def client_session_list(client):
    red = '\033[31m * \033[0m'
    green = '\033[32m * \033[0m'
    try:
        res = client.service.get_sessions(client.sid)
    except Exception, e:
        if type(e.message) == tuple and len(e.message) == 2 \
                and e.message[1] == 'Forbidden':
            print _("Access forbidden!")
        else:
            print e
        return 1
    if hasattr(res, 'string'):
        if res.string:
            print _('Active sessions on the server: ')
            for session_id in res.string:
                print green + session_id
            print
            return 0
    print red + _('No active sessions on the server')


def session_clean(client):
    try:
        res = client.service.clear_session_cache(client.sid)
        if res:
            print _('Error clearing the session cache')
        else:
            print _('Session cache cleared')
    except Exception as e:
        if type(e.message) == tuple and len(e.message) == 2 \
                and e.message[1] == 'Forbidden':
            print _("Access forbidden!")
        else:
            print e


class SessionId(object):
    SID_FILE = None
    HOST = None
    SID_LOCK = None

    def get_sid(self):
        if not os.path.exists(self.SID_FILE):
            return "0"
        else:
            with Locker(fn=self.SID_LOCK):
                for line in readLinesFile(self.SID_FILE):
                    data = line.split()
                    if len(data) == 2:
                        host, sid = data
                        if self.host_alias(self.HOST) == host:
                            return sid
        return "0"

    def host_alias(self, host):
        if host == "localhost":
            return "127.0.0.1"
        return host

    def write_sid(self, sid):
        with Locker(fn=self.SID_LOCK):
            sid_data = readFile(self.SID_FILE)
            added = False
            with writeFile(self.SID_FILE) as f:
                for line in sid_data.split('\n'):
                    data = line.split()
                    if len(data) == 2:
                        host, oldsid = data
                        if self.host_alias(self.HOST) == host:
                            oldsid = str(sid)
                            added = True
                        f.write("%s %s\n" % (host, oldsid))
                if not added:
                    f.write("%s %s" % (self.host_alias(self.HOST), str(sid)))
