# -*- 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 calculate.console.application.function import _print

import sys
import datetime
from calculate.lib.utils.tools import classificate

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

setLocalTranslate('cl_console3', sys.modules[__name__])
client_types = "console"


def pid_inf(client, sid, pids, wait_thread=None):
    """ get and show information about process """
    for mark, pid in classificate(pids):
        s = client.service.pid_info(sid, pid)
        if wait_thread:
            wait_thread.stop()
            sys.stdout.write("\b")
            sys.stdout.flush()
        if s == "":
            print _("PID not found")
            return 1
        if s[0][0] == "Permission denied":
            print _("Permission denied")
            return 1

        _print(_(u"Process name: %s") % s[0][4])
        print _(u"ID: %s") % s[0][0]
        _print(_(u"Start time: %s") % s[0][2].partition(".")[0])
        if s[0][1] == '1':
            status = _(u"Active")
        elif s[0][1] == '0':
            status = _(u"Completed")
        else:
            status = _(u"Killed")
        print _(u"Status: %s") % status
        if not mark.last:
            print
    return 0


def client_list_pid(client):
    """ get all process id for this session """
    sid = client.get_sid()

    red = '\033[31m * \033[0m'
    green = '\033[32m * \033[0m'
    try:
        list_pid = client.service.list_pid(sid=sid)
        if list_pid[0][0] == 0:
            print red + _("PIDs not found for this session!")
            return 0
        else:
            for i in list_pid[0]:
                print green + "pid - %d" % i
    except Exception:
        print red + _("Error fetching the PID list from the server")
        return 1
    return len(list_pid[0])


def gen_pid_ls(client):
    """ generation list with pid for this session """
    sid = client.get_sid()
    pid_ls = []
    try:
        list_pid = client.service.list_pid(sid=sid)
        if list_pid[0][0] == 0:
            print _("PIDs not found for this session!")
            return 0
        else:
            for i in list_pid[0]:
                pid_ls.append(i)
    except Exception:
        print _("Error fetching the PID list from the server")
        return 0
    return pid_ls


def client_pid_info(client, wait_thread=None):
    """ get information about selected process (or about all) """
    sid = client.get_sid()
    pid_ls = gen_pid_ls(client)
    if wait_thread:
        wait_thread.stop()
        sys.stdout.write("\b")
        sys.stdout.flush()
    if pid_ls:
        pid_inf(client, sid, pid_ls, wait_thread=wait_thread)


def client_list_methods(client):
    """ get & show all available methods for this certificate """
    DAT = 0  # Access to data soap structure
    RES = 0  # Access to result
    COM = 0  # Getting command line
    METH = 1  # Getting method line
    TR_METH = 3  # Translate method name
    results = client.service.get_methods(client.sid, client_types)
    if not results:
        print _('No methods available')
        return 1
    try:
        if results[DAT][RES][RES][COM] == '0':
            print _('No methods available')
            return 1
    except:
        pass
    print _("Available methods:")
    group_dict = {}
    for group in results.stringArray:
        if len(group.string) == 4:
            group_dict[group.string[METH]] = group.string[TR_METH]
        if len(group.string) == 3:
            group_dict[group.string[METH]] = group.string[TR_METH - 1]
    sort_keys = group_dict.keys()
    sort_keys.sort()
    for key in sort_keys:
        print "   %s - %s" % (key, group_dict[key])


def client_pid_kill(client, pid):
    sid = client.get_sid()

    result = client.service.pid_kill(pid, sid)
    if result == 0:
        print _("Process completed")
    elif result == 2:
        print _("Process killed")
    elif result == 3:
        print _("Process not found")
    elif result == -1:
        print _("Certificate not found on the server")
    elif result == -2:
        print _("Session not matching your certificate")
    elif result == 1:
        print _("Failed to terminate the process")
    return 0
