# -*- 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 __future__ import absolute_import
from calculate.core.server.loaded_methods import LoadedMethods

import calculate.contrib
from spyne import String, Integer, Boolean
from spyne.model.primitive import string_encoding
from spyne import Array, ComplexModel
# from spyne.model import Mandatory 
from spyne import rpc



import sys
import pickle
import os
from calculate.lib.datavars import SourceReadonlyVariable
from calculate.core.server.core_interfaces import CoreServiceInterface

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

setLocalTranslate('cl_core3', sys.modules[__name__])
String.Attributes.encoding = "utf-8"
#####
# API
#####
class CommonInfo(ComplexModel):
    """
    Common info for all Info classes

    cl_templates_locate - templates location
    cl_dipatch_conf - update config method
    cl_verbose_set - display appling templates
    """
    cl_templates_locate = Array(String)
    cl_dispatch_conf = String
    cl_verbose_set = Boolean

    Default = Array(String)
    CheckAll = Boolean

class LazyString(object):
    pass


class DataVarsSerializer(ComplexModel):
    """Serializer for datavars types"""

    class Attributes(ComplexModel.Attributes):
        default = None
        min_occurs = 1

    def elementByType(self, typeobj):
        """Get element by variable type, given for table or not"""
        elementMap = {'table': 'table',
                      "string": "input",
                      "bool": "check",
                      "boolauto": "check_tristate",
                      "bool3": "check_tristate",
                      "choice": "combo",
                      "choiceedit": "comboEdit",
                      "choiceedit-list": "multichoice_add",
                      "choice-list": "multichoice",
                      "bool-list": "multichoice",
                      "list": "multichoice_add",
                      "password": "password",
                      "onepassword": "password",
                      "need-onepassword": "password",
                      "need-password": "password"}
        return elementMap.get(typeobj, 'input')

    def arrayString(self, value):
        if type(value) in (list, tuple):
            return [""] + map(lambda x: (",".join(x)
                                         if type(x) in (list, tuple)
                                         else x),
                              value)
        else:
            return value

    def arrayArrayString(self, value):
        if type(value) in (list, tuple):
            return map(self.arrayString, value)
        else:
            return value

    def getChoice(self, var_obj):
        if ("choice" in var_obj.type or "file" in var_obj.type or
                    var_obj.element == "radio"):
            choice, comments = var_obj.parent.ChoiceAndComments(var_obj.name)
            return self.arrayString(choice), self.arrayString(comments)
        else:
            return None, None


class ChoiceValue(DataVarsSerializer):
    typefield = String(default=None, min_occurs=1)
    values = Array(String, default=None, min_occurs=1)
    comments = Array(String, default=None, min_occurs=1)
    onChanged = Array(String, default=None, min_occurs=1)

    def __init__(self, dv=None, varObj=None, readOnly=False, **kwargs):
        if dv:
            super(ChoiceValue, self).__init__()
            if not readOnly:
                self.values, self.comments = self.getChoice(varObj)
            elif isinstance(varObj, SourceReadonlyVariable):
                items = varObj.getMapHumanReadable().items()
                if items:
                    self.values, self.comments = zip(*items)
                else:
                    self.values, self.comments = [], []
                self.values = self.arrayString(self.values)
                self.comments = self.arrayString(self.comments)
            if varObj.mode == 'w':
                self.typefield = (varObj.element or
                                  self.elementByType(varObj.type))
            else:
                if readOnly:
                    self.typefield = "readonly"
                else:
                    self.typefield = "text"
        else:
            super(ChoiceValue, self).__init__(**kwargs)

    def elementByType(self, typeobj):
        """Get element by variable type, given for table or not"""
        if "-list" in typeobj:
            typeobj = typeobj.replace("-list", "", 1)
        elif "list" in typeobj:
            typeobj = typeobj.replace("list", "", 1)
        return DataVarsSerializer.elementByType(self,
                                                typeobj)


class Table(DataVarsSerializer):
    # head = Mandatory(Array(String(default=None, min_occurs=1), min_occurs=1))
    head = Array(String(default=None, min_occurs=1), min_occurs=1)
    fields = Array(String(default=None, min_occurs=1), min_occurs=1)  # name fields in params object
    body = Array(Array(String), default=None, min_occurs=1)
    values = Array(ChoiceValue, default=None, min_occurs=1)
    onClick = String(default=None, min_occurs=1)
    addAction = String(default=None, min_occurs=1)
    # шаг на который нужно прейти при выполнении onClick
    step = String(default=None, min_occurs=1)
    # количество записей в таблице
    records = String(default=None, min_occurs=1)

    def __init__(self, dv=None, briefmode=None,
                 varObj=None, head=None, body=None, values=None,
                 fields=None, onClick=None, addAction=None, step=None,
                 records=None):
        super(Table, self).__init__()
        # print("DEBUG Table init")

        if dv:
            self.head = []
            self.body = []
            self.values = []
            # get information about all table columns
            self.writable = True
            for i, col in enumerate(varObj.source):
                # get columns variable obj
                varSource = dv.getInfo(col)
                # invalidate columns vars for uncompatible table
                if varSource.uncompatible():
                    dv.Invalidate(col, onlySet=True)
                # header label
                self.head.append(varSource.label or varSource.name)
                # if column writable then add ChoiceValue info
                if varSource.mode == 'w' or i == 0:
                    self.values.append(ChoiceValue(dv, varSource))
                    if varSource.mode == 'r' and i == 0:
                        self.writable = False
                else:
                    self.values.append(
                        ChoiceValue(dv, varSource, readOnly=True))
            # get table body
            # empty value at start add for fix data transfer
            self.body = self.arrayArrayString(
                dv.Get(varObj.name, humanreadable=True if briefmode else False))
        else:
            self.head = head
            self.fields = fields
            self.body = body
            self.values = values
            self.onClick = onClick
            self.addAction = addAction
            self.step = step or "0"
            self.records = records or "0"


class Option(DataVarsSerializer):
    shortopt = String(default=None, min_occurs=1)
    longopt = String(default=None, min_occurs=1)
    metavalue = String(default=None, min_occurs=1)
    syntax = String(default=None, min_occurs=1)
    help = String(default=None, min_occurs=1)

    def __init__(self, optlist, metaval, helpval, syntax=""):
        super(Option, self).__init__()
        self.help = helpval
        self.metavalue = metaval
        self.syntax = syntax
        for val in optlist:
            if val.startswith('--'):
                self.longopt = val
            else:
                self.shortopt = val


class Field(DataVarsSerializer):
    name = String(default=None, min_occurs=1)  # varname from Datavars
    label = String(default=None, min_occurs=1)  # label for GUI
    type = String(default=None, min_occurs=1)  # data type of variable
    opt = Option # opt for cmdline
    help = String(default=None, min_occurs=1)  # help for cmdline (GUI?)
    element = String(default=None, min_occurs=1)  # type element
    guitype = String(default=None, min_occurs=1) # addon guitype
    choice = Array(String, default=None, min_occurs=1)  # value (combobox,comboedit)
    listvalue = Array(String, default=None, min_occurs=1)  # current listvalue
    default = Boolean(default=None, min_occurs=1)  # default value or False
    value = String(default=None, min_occurs=1)  # current value
    tablevalue = Table  # current table value
    uncompatible = String(default=None, min_occurs=1)  # message for uncompatibility variable
    comments = Array(String, default=None, min_occurs=1) # comments for choice

    def __init__(self, dv=None, varObj=None, expert=False, briefmode=False,
                 inbrief=False, groupVars=(), onlyhelp=False, **kwargs):
        """
        dv - datavars, varObj - current variable, expert - expert variable flag,
        briefmode - view request for brief, inbrief - variable palced in brief,
        """
        if dv:
            super(Field, self).__init__()
            self.name = varObj.name
            self.type = varObj.type
            if varObj.opt:
                self.opt = Option(varObj.opt, varObj.metavalue, varObj.help,
                                  varObj.syntax)
            self.help = varObj.help
            self.element = varObj.element or self.elementByType(self.type)
            self.label = str(varObj.label or varObj.name)
            self.guitype = varObj.guitype
            if (not onlyhelp or varObj.syntax or self.type == "table" or
                        self.type == "bool"):
                if inbrief:
                    self.uncompatible = ""
                else:
                    self.uncompatible = dv.Uncompatible(varObj.name)
                if self.uncompatible:
                    # блок используется для отмены пометки о несовместимости
                    # если несовместимая переменная, и та из-за которой
                    # она является несовместимой находятся  на одной и той же
                    # странице (например доступность MBR зависит от опции UEFI,
                    # они находятся на одной и той же странице)
                    for var in varObj.reqUncompat:
                        if not briefmode and var in groupVars:
                            if not dv.Uncompatible(var.name):
                                self.uncompatible = ""
                                break
                    else:
                        dv.Invalidate(varObj.name, onlySet=True)
                if expert:
                    self.default = not varObj.wasSet
                self.choice, self.comments = self.getChoice(varObj)
                if self.type == "table":
                    # print("DEBUG_table creation")

                    self.tablevalue = Table(dv=dv, briefmode=briefmode,
                                            varObj=varObj)
                    if self.tablevalue.writable:
                        self.type = "writable"
                else:
                    full_varname = "%s.%s" % (varObj.section, varObj.name)
                    value = dv.Get(full_varname)
                    if type(value) in (list, tuple):
                        if briefmode and "choice" not in self.type:
                            self.value = dv.Get(full_varname,
                                                humanreadable=True)
                        self.listvalue = self.arrayString(value)
                    else:
                        if briefmode:  # and not "choice" in self.type:
                            self.value = dv.Get(full_varname,
                                                humanreadable=True)
                        else:
                            self.value = value
                            # if self.value:
                            #    self.default = self.value
        else:
            super(Field, self).__init__(**kwargs)


class GroupField(DataVarsSerializer):
    name = String(default=None, min_occurs=1)
    fields = Array(Field, default=None, min_occurs=1)
    prevlabel = String(default=None, min_occurs=1)
    nextlabel = String(default=None, min_occurs=1)
    last = Boolean(default=None, min_occurs=1)

    def __init__(self, name="", fields=list(), prevlabel="",
                 nextlabel="", last=False, dv=None, info=None,
                 expert=False, brief=False, onlyhelp=False):
        super(GroupField, self).__init__()
        self.last = last
        if dv:
            self.name = info['name']
            if not onlyhelp:
                self.nextlabel = info['next_label']
                self.prevlabel = _("Previous")
            else:
                self.nextlabel = None
                self.prevlabel = None
            self.fields = []

            # get all variables with deps which using in this group
            groupDepVars = []
            from itertools import chain

            for varname in chain(info['normal'], info['expert']):
                for var in dv.getRequired(varname):
                    if var not in groupDepVars:
                        groupDepVars.append(var)

            if brief:
                uniqBrief = list(info['brief']) + [x for x in
                                                   info['brief_force']
                                                   if x not in info['brief']]
                for varname in uniqBrief:
                    varObj = dv.getInfo(varname)
                    inbrief = varname in info['brief_force']
                    self.fields.append(Field(dv=dv, inbrief=inbrief,
                                             briefmode=brief,
                                             varObj=varObj,
                                             groupVars=groupDepVars,
                                             onlyhelp=onlyhelp))
            else:
                uniqBrief = []
            for varname in (x for x in info['normal'] if x not in uniqBrief):
                inbrief = brief and varname in info['brief_force']
                if brief and 'hide' in info and varname in info['hide']:
                    continue
                varObj = dv.getInfo(varname)
                self.fields.append(Field(dv=dv, inbrief=inbrief,
                                         briefmode=brief,
                                         varObj=varObj,
                                         groupVars=groupDepVars,
                                         onlyhelp=onlyhelp))
            if info['expert']:
                for varname in (x for x in info['expert'] if
                                x not in uniqBrief):
                    if expert is True or expert is None and dv.getInfo(
                            varname).wasSet:
                        self.fields.append(Field(name="expert",
                                                 element="expert",
                                                 label=str(info['expert_label']),
                                                 value="open"))
                        for varname_ in info['expert']:
                            inbrief = brief and varname_ in info['brief_force']
                            if (brief and 'hide' in info and
                                        varname_ in info['hide']):
                                continue
                            varObj = dv.getInfo(varname_)
                            self.fields.append(Field(dv=dv, expert=True,
                                                     inbrief=inbrief,
                                                     briefmode=brief,
                                                     varObj=varObj,
                                                     groupVars=groupDepVars,
                                                     onlyhelp=onlyhelp))
                        break
                else:
                    if expert is False:
                        for varname in info['expert']:
                            vn = varname.rpartition('.')[2]
                            dv.Invalidate(vn, True)
                    if not onlyhelp:
                        self.fields.append(Field(name="expert",
                                                 element="expert",
                                                 label=str(info['expert_label']),
                                                 value="close",
                                                 onlyhelp=onlyhelp))
        else:
            self.name = name
            self.fields = fields
            self.nextlabel = nextlabel


class ViewInfo(DataVarsSerializer):
    groups = Array(GroupField, default=None, min_occurs=1)
    has_brief = Boolean(default=None, min_occurs=1)

    def __init__(self, datavars=None, step=None, expert=None, allsteps=False,
                 brief=None, brief_label=None, has_brief=False, groups=list(),
                 viewparams=None):
        super(ViewInfo, self).__init__()
        onlyhelp = False
        if viewparams:
            # for compatible specifing step by param
            step = viewparams.step if step is None else step
            expert = viewparams.expert if expert is None else expert
            brief = viewparams.brief if brief is None else brief
            onlyhelp = viewparams.onlyhelp
        self.has_brief = has_brief

        if datavars:
            self.groups = []
            varGroups = datavars.getGroups()
            lastGroup = len(varGroups) - 1
            # interate all vars group
            if step in (0, -1, None) or allsteps:
                briefData = datavars.getBrief()
                # print("DEBUG viewInfo")
                # print("var groups: %s " % bool(varGroups))
                # print(datavars)
                self.groups.append(self.stepGroup(varGroups, brief_label,
                                                  help_value=briefData.get(
                                                      "help", None),
                                                  next_value=briefData.get(
                                                      "next", None),
                                                  image_value=briefData.get(
                                                      "image", "")))
            for i, groupInfo in enumerate(varGroups):
                if step in (None, -1) or step == i:
                    # print("viewInfo step %s " % i)

                    self.groups.append(GroupField(dv=datavars, info=groupInfo,
                                                  last=(lastGroup == i),
                                                  expert=expert,
                                                  brief=brief,
                                                  onlyhelp=onlyhelp))
                    if groupInfo['custom_buttons']:
                        for but in groupInfo['custom_buttons']:
                            if len(but) > 4:
                                listval = but[4]
                            else:
                                listval = None
                            if len(but) > 5:
                                f = but[5]
                                if f is None or callable(f) and f(datavars.Get):
                                    enable = True
                                else:
                                    enable = False
                            else:
                                enable = True
                            self.groups[-1].fields.append(Field(
                                name=but[0], label=but[1], value=but[2],
                                element=but[3], listvalue=listval,
                                guitype=None if enable else "readonly"))

        else:
            self.groups = groups

    def stepGroup(self, groupInfo, brief_label, help_value=None,
                  next_value=None, image_value=""):
        """Step group"""
        # print("DEBUG what are you doing stepGroup")
        # print(groupInfo)
        # print(brief_label)
        return GroupField(fields=[
            Field(name="Steps",
                  element="table",
                  label=brief_label,
                  type='steps',
                  help=help_value,
                  value=next_value,
                  tablevalue=Table(
                      head=[i['name'] for i in groupInfo],
                      fields=[i.get('image', '')
                              for i in groupInfo] + [image_value],
                      body=[self.arrayString(
                          list(i['normal']) + [""] + list(i['expert']))
                            for i in groupInfo]))])

        # element = ['table', 'radio', 'combo', 'comboEdit', 'multichoice', \
        # 'multichoice_add', 'check', 'check_tristate', 'expert', 'input']


class ViewParams(ComplexModel):
    """
    Struct for _view methods
    """
    step = Integer(default=None, min_occurs=1)  # number of group variables
    expert = Boolean(default=None, min_occurs=1)  # request expert variables
    brief = Boolean(default=None, min_occurs=1)  # request brief variables
    onlyhelp = Boolean(default=None, min_occurs=1)  # request params for only help
    help_set = Boolean(default=None, min_occurs=1)  # set cl_help_set to on
    conargs = Array(String, default=None, min_occurs=1)  # set cl_console_args
    dispatch_usenew = Boolean(default=None, min_occurs=1)  # set cl_dispatch_conf to usenew
    clienttype = String(default=None, min_occurs=1)  # type of client "gui","console"


#########
# MESSAGE
#########
class ReturnedMessage(ComplexModel):
    type = String(default=None, min_occurs=1)
    field = String(default=None, min_occurs=1)
    message = String(default=None, min_occurs=1)
    expert = Boolean(default=None, min_occurs=1)
    field_obj = Field

    def __init__(self, type=None, field=None, message=None,
                 expert=False, field_obj=None):
        super(ReturnedMessage, self).__init__()
        self.type = type
        self.field = field
        self.message = message
        self.expert = expert
        if field_obj:
            self.field_obj = Field(dv=field_obj.parent, varObj=field_obj)
        else:
            self.field_obj = None


class Message(ComplexModel):
    type = String(default=None, min_occurs=1)
    message = String(default=None, min_occurs=1)
    id = Integer(default=None, min_occurs=1)
    result = Boolean(default=None, min_occurs=1)
    onlyShow = String(default=None, min_occurs=1)
    default = String(default=None, min_occurs=1)

    def __init__(self, type='normal', message=None, id=None,
                 result=None, onlyShow=None, default=None):
        super(Message, self).__init__()
        self.type = type
        self.message = message
        self.id = id
        self.result = result
        self.onlyShow = onlyShow
        self.default = default


class ReturnProgress(ComplexModel):
    percent = Integer(default=None, min_occurs=1)
    short_message = String(default=None, min_occurs=1)
    long_message = String(default=None, min_occurs=1)
    control = Integer(default=None, min_occurs=1)

    def __init__(self, percent=0, short_message=None, long_message=None,
                 control=None):
        super(ReturnProgress, self).__init__()
        self.percent = percent
        self.short_message = short_message
        self.long_message = long_message
        self.control = control


class Frame(ComplexModel):
    values = Array(Message, default=None, min_occurs=1)


# get and send client messages
class CoreWsdl(CoreServiceInterface):
    perm_denied = [Message(type='error', message='403 Forbidden')]
    @staticmethod
    def callAction(cls, sid, info, logicClass=None,
                   method_name=None, actionClass=None,
                   callbackRefresh=lambda sid, dv: True,
                   invalidators=None, depend_methods=()):
        """
        Общий алгоритм вызова действия
        """
        if not logicClass:
            logicClass = {}
        dv = cls.get_cache(sid, method_name, "vars")
        try:
            if not dv:
                dv = getattr(cls, "%s_vars" % method_name)()
            else:
                callbackRefresh(cls, sid, dv)
                dv.processRefresh()
            checkonly = False
            checkall = False
            if info and hasattr(info, "CheckOnly"):
                checkonly = info.CheckOnly
            if info and not hasattr(info, "CheckOnly"):
                checkall = True
            elif info and hasattr(info, "CheckAll"):
                checkall = info.CheckAll
            errors = map(lambda x: ReturnedMessage(**x),
                         dv.checkGroups(info,
                                        allvars=checkall or not checkonly,
                                        invalidators=invalidators))
            # if dv.Get('cl_env_debug_set') == 'on':
            #    dv.printGroup(info)
            if errors:
                return errors
            if checkonly:
                returnmess = ReturnedMessage(type='', message=None)
                return [returnmess]
            if not actionClass:
                return []
            objs = {}
            from calculate.core.server.func import CommonLink

            if isinstance(logicClass, dict):
                for k, v in logicClass.items():
                    objs[k] = type("Logic", (CommonLink, v, object), {})()
            install_meth = type("CommonCore", (cls.Common,
                                               actionClass, object), {})
            pid = cls.startprocess(cls, sid, target=install_meth,
                                    method="run",
                                    method_name=method_name,
                                    args_proc=(objs, dv,))
            returnmess = ReturnedMessage(type='pid', message=pid)
            returnmess.type = "pid"
            returnmess.message = pid
            cls.clear_cache(sid, method_name)
            cache_cleared = [method_name]
            clear_list = list(LoadedMethods.methodDepends[method_name])
            while clear_list:
                method_clear_name = clear_list.pop()
                if method_clear_name not in cache_cleared:
                    clear_list.extend(
                        LoadedMethods.methodDepends[method_clear_name])
                    cls.clear_cache_method(method_clear_name)
                    cache_cleared.append(method_clear_name)
            dv = None
            return [returnmess]
        finally:
            if dv:
                # print "Set cache", dv.Get('ur_unix_group_name_exists')
                cls.set_cache(sid, method_name, "vars", dv, smart=False)

    @staticmethod
    def fixInstallLocalization(cls, sid, dv):
        """
        Метод смены локализации интерфейса на лету (во время выбора
        параметров метода)
        """
        # print("DEBUG fixInstallLocalization")
        # print(dv)
        if "--start" not in sys.argv:
            return False
        import threading

        curThread = threading.currentThread()
        curThread.lang = dv.Get('install.os_install_locale_lang')
        # print("LOCALE DEBUG: thread lang: %s" % curThread.lang)
        currentLang = cls.get_cache(sid, "install", "lang")
        # print("LOCALE DEBUG: cached lang: %s" % currentLang)
        if currentLang != curThread.lang:
            dv.clearGroups()
            cls.install_vars(cls, dv)
            dv.reinit()
            return True
        else:
            return False

    # verification of compliance certificate and process (pid)
    @staticmethod
    def check_cert_pid(cls, sid, pid):
        import threading

        curThread = threading.currentThread()
        cert = curThread.client_cert

        from .cert_cmd import find_cert_id

        cert_id = find_cert_id(cert, cls.data_path, cls.certbase)
        cert_id = int(cert_id)
        if cert_id == 0:
            return 0

        # session file
        if not os.path.exists(cls.sids):
            os.system('mkdir %s' % cls.sids)

        check = 0
        try:
            fd = open(cls.sids_file, 'r')
        except IOError:
            return 0
        while 1:
            try:
                # read all on one record
                list_sid = pickle.load(fd)
            except (EOFError, KeyError, IOError):
                break
            # find session id in sids file
            if cert_id == int(list_sid[1]):
                if sid == int(list_sid[0]):
                    check = 1

        if check == 0:
            return 0
        fd = open(cls.sids_pids, 'r')
        while 1:
            try:
                # read out on 1 record
                list_pid = pickle.load(fd)
            except (EOFError, KeyError, IOError):
                break
            if sid == int(list_pid[0]):
                if pid == int(list_pid[1]):
                    fd.close()
                    return 1
        fd.close()
        return 0

    # send to client all new message
    @staticmethod
    def process_messages(cls, pid, client_type):
        result = []
        while len(cls.glob_frame_list[pid]) > \
                cls.glob_process_dict[pid]['counter']:
            item = cls.glob_process_dict[pid]['counter']
            only_show = cls.glob_frame_list[pid][item].onlyShow
            if (not client_type or
                    not only_show or only_show == client_type):
                result.append(cls.glob_frame_list[pid][item])
            cls.glob_process_dict[pid]['counter'] += 1
        return result

    # send to client new message from frame
    @staticmethod
    def client_get_frame(cls, sid, pid, client_type):
        if cls.check_cert_pid(cls, sid, pid):
            return cls.process_messages(cls, pid, client_type)
        return CoreWsdl.perm_denied

    # send to client new message from frame
    @staticmethod
    def client_get_entire_frame(cls, sid, pid):
        if cls.check_cert_pid(cls, sid, pid):
            try:
                results = cls.glob_frame_list[pid]
            except (AttributeError, KeyError, IndexError):
                return CoreWsdl.perm_denied
            len_glob_frame_list = len(cls.glob_frame_list[pid])
            cls.glob_process_dict[pid]['counter'] = len_glob_frame_list
            return results
        return CoreWsdl.perm_denied

    @staticmethod
    def client_get_table(cls, sid, pid, id):
        if cls.check_cert_pid(cls, sid, pid):
            return cls.glob_table_dict[pid][id]
        return CoreWsdl.perm_denied

    @staticmethod
    def client_get_progress(cls, sid, pid, id):
        if cls.check_cert_pid(cls, sid, pid):
            return cls.glob_progress_dict[pid][id]
        return ReturnProgress(0, control=403)
    
    @staticmethod
    # get message from client
    def client_send_message(cls, sid, pid, text):
        if cls.check_cert_pid(cls, sid, pid):
            cls.glob_process_dict[pid]['answer'] = text
            return Message(type='normal', message="")
        return CoreWsdl.perm_denied



class WsdlAdapter(object):
    adapted_class = None

    def __init__(self, source):
        self.source = source

    @classmethod
    def from_detect(cls, source):
        if isinstance(source, (cls.adapted_class, WsdlAdapter)):
            return source
        else:
            return cls(source)

    def __getattr__(self, item):
        return getattr(self.source, item)

    @staticmethod
    def Array(field, field_type):
        def wrapper(self):
            if getattr(self.source, field):
                return [field_type(x)
                        for x in getattr(getattr(self.source, field),
                                         field_type.__name__[:-7])]
            else:
                return []

        return property(wrapper)

    @staticmethod
    def StringArray(field):
        def wrapper(self):
            source_field = getattr(self.source, field)
            return source_field.string if source_field else []

        return property(wrapper)


class ChoiceValueAdapter(WsdlAdapter):
    adapted_class = ChoiceValue

    values = WsdlAdapter.StringArray("values")

    comments = WsdlAdapter.StringArray("comments")

    onChanged = WsdlAdapter.StringArray("onChanged")


class TableAdapter(WsdlAdapter):
    adapted_class = Table

    fields = WsdlAdapter.StringArray("fields")
    head = WsdlAdapter.StringArray("head")

    @classmethod
    def get_matrix(cls, value):
        if hasattr(value, 'stringArray'):
            return [row.string
                    for row in value.stringArray
                    if hasattr(row, "string")]
        elif isinstance(value, list):
            return value
        return []

    @property
    def body(self):
        return self.get_matrix(self.source.body)

    values = WsdlAdapter.Array("values", ChoiceValueAdapter)


class FieldAdapter(WsdlAdapter):
    adapted_class = Field

    choice = WsdlAdapter.StringArray("choice")
    listvalue = WsdlAdapter.StringArray("listvalue")
    comments = WsdlAdapter.StringArray("comments")

    @property
    def tablevalue(self):
        return TableAdapter(self.source.tablevalue)


class GroupFieldAdapter(WsdlAdapter):
    adapted_class = GroupField

    fields = WsdlAdapter.Array("fields", FieldAdapter)


class ViewInfoAdapter(WsdlAdapter):
    adapted_class = ViewInfo

    groups = WsdlAdapter.Array("groups", GroupFieldAdapter)


class ArrayReturnedMessage(WsdlAdapter):
    @classmethod
    def from_detect(cls, source):
        if isinstance(source, (list, tuple)):
            return source
        else:
            return source.ReturnedMessage
