#-*- 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 more import get_sid
from PySide import QtGui
from ReturnMessage import ReturnedMessage

import urllib2
#class ret_mes():
#    def __init__ (self, pid):
#        self.type = "pid"
#        self.message = pid

def show_msg(text, title = None, parent = None):
    msgBox = QtGui.QMessageBox(parent)
    if title:
        msgBox.setWindowTitle(title)
    if not text:
        return 1
    if not type(text) in [str,unicode]:
        temp = ''
        for i in text:
            try:
                temp += str(i).decode('utf-8')+' '
            except (UnicodeEncodeError, UnicodeDecodeError):
                temp += str(i)+' '
        text = temp
    msgBox.setText(text)
    msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
    msgBox.setWindowIcon (QtGui.QIcon('calculate-install.svg'))
    msgBox.exec_()

client_types = "gui"
                             
def client_list_pid(client):
    """ get all process id for this session """
    sid = get_sid(client)
    try:
        list_pid = client.service.list_pid(sid = sid)
        if list_pid[0][0] == 0:
            return []
        else:
            return list_pid[0]
    except:
        _print (_("Failed to get the PID list from the server"))
        return []

def gen_pid_ls(client):
    """ generation list with pid for this session """
    try:
        list_pid = client_list_pid(client)
        if not list_pid:
            return 0
    except:
        return 0
    return list_pid

def pid_inf(ClientObj, client, sid, pids):
    """ get and show information about process """
    for pid in pids:
        try:
            s = client.service.pid_info(sid, pid)
        except urllib2.URLError:
            _print ('client.service.pid_info in pid_inf Exception')
            return 1
        if s == "":
            show_msg (_("PID %d not found") %pid)
            return 1
        if s[0][0] == "Permission denied":
            show_msg (_("Permission denied"))
            return 1
        pid_str = str(pid)

        # Create info about process (process_dict)
        ClientObj.process_dict[pid_str] = {}
        ClientObj.process_dict[pid_str]['time'] = str(s[0][2])
        ClientObj.process_dict[pid_str]['name'] = str(s[0][3])
        if s[0][4] != 'None':
            ClientObj.process_dict[pid_str]['method_name'] = str(s[0][4])
        else:
            ClientObj.process_dict[pid_str]['method_name'] = str(s[0][3])
            
        ClientObj.process_dict[pid_str]['status'] = s[0][1]
        ClientObj.process_dict[pid_str]['result'] = \
                        ReturnedMessage("pid", None, pid_str)
#        ClientObj.process_dict[pid_str]['layout'] = QtGui.QVBoxLayout()

def client_pid_info(ClientObj, client, pid):
    """ get information about selected process (or about all) """
    pid = int (pid)
#    try:
    pid_get = []
    pid_get.append(pid)
    sid = get_sid(client)
    if pid > 0:
        pid_inf(ClientObj, client, sid, pid_get)
    elif pid == 0:
        pid_ls = gen_pid_ls(client)
        if pid_ls:
            pid_inf(ClientObj, client, sid, pid_ls)
#    except:
#        show_msg("Error get process information")
#        return 1
    return 0
