#-*- coding: utf-8 -*-

# Copyright 2010-2012 Calculate Ltd. 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 sys, time

from soaplib.serializers.primitive import String, Integer, Boolean
from soaplib.serializers.clazz import Array, ClassSerializer
from soaplib.service import rpc

from calculate.core.server.api_types import (ChoiceValue, Table, Field,
                                             GroupField, ViewInfo, ViewParams,
                                             ReturnedMessage, Option)

from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_core3',sys.modules[__name__])

class SH (ClassSerializer):
    name = String
    times = Integer
    boolvariable = Boolean
    boolvariable2 = Boolean
    radiovariable = String
    radiovariable2 = String
    combovariable = String
    combovariable2 = String
    comboEdit1 = String
    comboEdit2 = String
    multichoice_add = Array(String)
    multichoice = Array(String)
    Partition_table = Array(Array(String))
    Partition_table2 = Array(Array(String))

    Steps = Array(Array(String))
    isopath = Array(String)
    isopath_file = String

    comboLang = String
    # for check parameters without call method
    CheckOnly = Boolean
    Default = Array(String)

class CoreWsdl:
    def say_hello_meth (self, name, times, town):
#        print 'name = ', name, 'times = ', times, 'town = ',town
        times = 4
        town = 'Piter'
        try:
            results = []
            self.writeFile()
            for i in range( 0, times ) :
                results.append('Hello!!!, %s %d'%(name, i))
            # Помещение данных в словарь процессов
            #self.briefParams('test_view')
            #ask = self.askQuestion('start method? yes/[no]:')
            #if not ask.lower() in ['y', 'yes']:
                #return True
            #self.setData (results)

            # ask password
            #passwd = self.askPassword('Enter Your Password: ', True)
            #if passwd == "www":
                #self.printERROR (_('Password Incorrect!'))
                #self.endFrame()
                #return False
            #self.printSUCCESS(_('Password is correct'))
            self.setTaskNumber(6)
            self.startTask("Formatting", True, num = 1)
            self.endTask()

            self.startTask("Copying files", True, num = 3)
            #self.addMessage(type = 'warning', message = 'enter Russian name! Not %s' %name)
            self.printWARNING('Not enough space on disk')
            #self.askPassword('Enter Your Password: ')
            # Учёт процесса выполнения
            perc = 0
            while self.getProgress() < 100:
                time.sleep(1)
                perc += 20
                #self.addMessage(type = 'warning', message = '%s%%' %perc)
                # Увеличение процента выполнения процесса
                if perc < 50:
                    #print 'looooong long message=)', perc
                    self.setProgress (perc, 'hello %d perc!' %perc, \
                                      'short message')
                else:
                    self.printERROR()
                    break
                    #print 'looooong long message=) veeeery', perc
#                    self.setProgress (perc, 'hello %d perc!' %perc, \
#                        'looooong long message=)')
            #question = self.askQuestion('enter name: ', None)
            #print question
            #print self.askPassword ('Please, your enter pass: ')
#            self.endTask(progress_message = 'Test work Completed!')

            #if not question in [None, "", []]:
            #head = [' ', question, 'two', question]
            #else:
            head = [town,'One','Two','Three','Four']
            body = [['One','11','12','13','14']]#,['Two','21','22','23','24'],\
                    #['Three','31','32','33','34'], ['Four','41','42','43','44']]

            #self.printTable("Table 1!", head, body)

            head = [town,'AAA','BBB','CCC','DDD']
            body = [['One','11','12','13','14'],['Two','21','22','23','24'],\
                    ['Three','31','32','33','34'], ['Four','41','42','43','44'],\
                    ['Three','31','32','33','34'], ['Four','41','42','43','44']]

            self.printTable("Table 2!", head, body)
            self.startTask("Umount Devices", True, num = 2)
            perc = 0
            while self.getProgress() < 100:
                time.sleep(0.3)
                perc += 10
                # Увеличение процента выполнения процесса
                self.setProgress (perc)
            self.printERROR ('you not entered country!')
            self.endTask("Message about error task 2!")
            self.endFrame()
            # necessary for correct complete the process
            return True
        # Обработка сигнала прерывания работы процесса
        except KeyboardInterrupt:
            try:
                # Необходимо передать Fasle для сохранения данных о процессе
                self.printERROR(_('Manually interrupted'))
                return False
            except KeyboardInterrupt:
                return False
        except:
            return False



    #def check_params (self, dv, rrr):
        #errors = []
        #for i in rrr.compliance:
            #if rrr.__getattribute__(i) != None:

                ##print '%%%%%%%%%%%%%%%%',i
                ##print rrr.__getattribute__(i)

                ##print '********', SH2.compliance[i]
                ##print rrr.__getattribute__(i)
                #try:
                    #dv.Set(SH2.compliance[i], rrr.__getattribute__(i))
                #except VariableError, e:
                    #mess = ''
                    #for error in e.message:
                        #mess += str(error) + '\n'
                    ##print i, mess
                    #errors.append(ReturnedMessage(type = 'error', field = i, \
                                #message = mess))
                #except ClDataVarsError, q:
                    #print q

        #return errors
                ##dv.Set('os_location_data',rrr.disk)

    from calculate.core.server.decorators import Dec

    @rpc(Integer, SH, _returns = Array(ReturnedMessage))
    @Dec.core_method(gui=True,title='First Test',category=_('Utilities')+\
          '.Test',image='/usr/share/wallpapers/Horos/contents/screenshot.png,'\
          'system-log-out', command='cl-test',rights=["test"])
    def test ( self, sid, rrr):
        #print '>>>>>>>', sid, rrr
        name_meth = 'test'
        #print "Default = ", rrr.Default
        self.set_cache(sid, name_meth, 'object', rrr)
        #if not rrr or not rrr.name and not rrr.times:
            #return [ReturnedMessage(type = 'error', field = 'name',
                                    #message = 'not sent value name')]
        if rrr.name == 'qqq':
            errors = []
            errors.append(ReturnedMessage(type = 'error', field = 'name', \
                                message = 'Do not input "qqq"vvv ddddddd dddddd!' + \
                                'input not @@@@@# $$$$$$$$ ^^^^^^^^^ ' + \
                                'input not @@@@@# $$$$$$$$ ^^^^^^^^^ ' + \
                                'input not @@@@@# $$$$$$$$ 44444444'))
            errors.append(ReturnedMessage(type = 'error', field = 'boolvariable', \
                                message = 'Choose this!'))
            return errors
        if rrr.radiovariable == 'Piter':
            errors = []
            errors.append(ReturnedMessage(type = 'error', field = 'radiovariable', \
                                message = 'Do not input "Piter"!'))

            return errors
        if rrr.CheckOnly:
            returnmess = ReturnedMessage(type = '', message = None)
            return [returnmess]
        if rrr.name == 'qqqq':
            errors = []
            errors.append(ReturnedMessage(type = 'error', field = 'name', \
                                message = 'not "qqqq" for step 2!'))
            errors.append(ReturnedMessage(type = 'error', field = 'boolvariable', \
                                message = 'Choose this!'))
            return errors
        #try:
            #print '====>', rrr.boolvariable
        #except:
            #print "====> ERROR"
        #town = rrr.combovariable
        #name = rrr.name
        #times = rrr.times
        sh = self.get_cache(sid, name_meth, 'object')
        if sh.name == 'qqqq':
            errors = []
            #errors.append(ReturnedMessage(type = 'error', field = 'name', \
                                #message = 'not "qqqq" for step 2!'))
            errors.append(ReturnedMessage(type = 'error', field = 'boolvariable', \
                                message = 'Choose this!'))
            return errors
        if sh == None:
            sh = SH()
            #sh.name = name
        times = sh.times
        name = sh.name
        sh.iii = 4
        town = sh.combovariable
        #print "------->>>", name, times, town
        self.set_cache(sid, name_meth, 'object', rrr)
        say_hello_meth = type("CommonInstall",(self.Common, CoreWsdl, object), {})
        name = sh.name

        pid = self.startprocess(sid, target=say_hello_meth, \
                                method="say_hello_meth", method_name='test', \
                                args_proc = (name, times, town))
        returnmess = ReturnedMessage(type = 'pid', message = pid)
        #returnmess.type = "pid"
        #returnmess.message = pid
        return [returnmess]

    @rpc(Integer, ViewParams, _returns = ViewInfo)
    def test_view (self, sid, vp):
        #print '%%%%%% test_view, step', vp.step
        #print "expert = ", vp.expert
        step = vp.step
        expert = vp.expert
        if step == 7:
            step = None
        if step in [0, None]:
            view = ViewInfo(groups=[], has_brief = True)

            group = GroupField(name=_("Test Method"), nextlabel="To step 2",
                               last=False)
            group.fields = []

            group.fields.append(Field(
                    name = "name",
                    label = "YOUR NAME: ",
                    type = "str",
                    value = '',
                    opt = Option(['-n','--name'], 'NAME', 'your name'),
                    help = \
                    "Please enter your name",
                    element = "input"))
            group.fields.append(Field(
                    name = "times",
                    label = _("Time: "),
                    #type = "int",
                    type = "int",
                    value = '55',
                    help = \
                    "Enter the time",
                    #uncompatible = 'Tool tip text',
                    element = "input"))
            group.fields.append(Field(
                    name = "isopath",
                    label = _("select an ISO"),
                    value = '/var/calculate',
                    type = 'files',
                    help = \
                    "Enter the time",
                    element = "openfile"))
            group.fields.append(Field(
                    name = "isopath_file",
                    label = "select an ISO",
                    choice = ['one', 'two'],
                    comments = ['first', 'second'],
                    value = '/home/guest/1',
                    type = 'files',
                    help = \
                    "Enter the time",
                    element = "file"))
            group.fields.append(Field(
                    name = "Partition_table",
                    label = _("Mount Points: "),
                    element = "table",
                    type = 'writable',
                    # Table
                    tablevalue = Table(
                    head = ['Partition','Mount Point','Filesystem', \
                                     'Perform format','Label','Size'],
                    body = [['/dev/sda1','swap','swap','off',None,'4G'],\
                            ['/dev/sda2','/','reiserfs','on','CLD','10G'],\
                            ['/dev/sda3','/var/calculate','ext4','off',
                             None,'30G']],
                    values = [ChoiceValue(
                            typefield = 'combo',
                            values = ['/dev/sda1','/dev/sda2','/dev/sda3'],
                            comments = ['disk1','disk2','disk3']),
                            #onChanged = ['nothing',None,'get_body','get_body',\
                                         #'get_body','get_body']),

                            ChoiceValue(
                            typefield = 'comboEdit',
                            values = ['/','swap','/var/calculate'],
                            comments = ['root','swap','calc']),

                            ChoiceValue(
                            typefield = 'multichoice_add',
                            values = ['swap','reiserfs','ext4'],
                            comments = ['swap1','reiserfs1','ext41']),

                            ChoiceValue(
                            typefield = 'check',
                            values = ['on','off']),

                            ChoiceValue(
                            typefield = 'text',
                            values = ['/dev/sda1','/dev/sda2','/dev/sda3'],
                            comments = ['3Gb','','disk3'])],
                    )))
            group.fields.append(Field(
                    name = "Steps",
                    element = "table",
                    type = 'steps',
                    label = 'Brief preview',
                    help = '<b><i>help</b></i>',
                    value = 'install',
                    # Table
                    listvalue = ['go-previous',' ','system-log-out'],
                    tablevalue = Table(
                    head = ['Табличка','Второй шаг','Завершение'],
                    fields = ['install','','welcome'],
                    body = [['times','name','isopath','Partition_table','',\
                            'boolvariable2','boolvariable', 'combovariable', \
                            'combovariable2'],\
                            ['radiovariable2','radiovariable','comboEdit1', \
                            'comboEdit2', 'multichoice_add', 'multichoice'], \
                            ['comboLang']]
                    )))
            if expert:
                group.fields.append(Field(
                        name = "expert_open",
                        #label = "Advanced settings...",
                        type = "label",
                        help = \
                        "you not human? This is a anti-bot test",
                        value = 'open',
                        element = "expert"))
                group.fields.append(Field(
                        name = "boolvariable",
                        label = "you BOT?",
                        type = "bool",
                        value = 'on',
                        default = True,
                        help = \
                        "you not human? This is a anti-bot test",
                        element = "check"))
                group.fields.append(Field(
                        name = "boolvariable2",
                        label = "you BOT?",
                        type = "bool",
                        value = 'auto',
                        default = True,
                        help = \
                        "you not human? This is a anti-bot test",
                        element = "check_tristate"))
                group.fields.append(Field(
                        name = "combovariable",
                        label = "check city number: ",
                        choice = ['Moscow-1','Piter-2','---','New York-3','London-4'],
                        comments = ['Mos','Pit','---','New Yo','Lond'],
                        type = "str",
                        default = True,
                        value = 'New York-3',
                        help = \
                        "you not human? This is a anti-bot test",
                        element = "combo"))
                group.fields.append(Field(
                        name = "combovariable2",
                        label = "check city number: ",
                        choice = ['Moscow','Piter','New York','---','London'],
                        type = "str",
                        value = 'London',
                        default = True,
                        help = \
                        "you not human? This is a anti-bot test",
                        element = "comboEdit"))
            else:
                group.fields.append(Field(
                        name = "expert_close",
                        #label = "Advanced settings...",
                        type = "label",
                        help = \
                        "you not human? This is a anti-bot test",
                        value = 'close',
                        element = "expert"))
            #group.fields.append(Field(
                    #name = "Partition_table2",
                    #label = _("Mount Points: "),
                    #element = "table",
                    ##type = 'writable',
                    ## Table
                    #tablevalue = Table(
                    #head = ['Partition','Mount Point','Filesystem', \
                                     #'Perform format','Label','Size'],
                    #body = [['/dev/sda1','swap','swap','off',None,'4G'],\
                            #['/dev/sda2','/','reiserfs','on','CLD','10G'],\
                            #['/dev/sda3','/var/calculate','ext4','off',None,'30G']],
                    #values = [ChoiceValue(
                            #typefield = 'combo',
                            #values = ['/dev/sda1','/dev/sda2','/dev/sda3'],
                            #onChanged = ['nothing',None,'get_body','get_body',\
                                         #'get_body','get_body']),

                            #ChoiceValue(
                            #typefield = 'comboEdit',
                            #values = ['/','swap','/var/calculate']),

                            #ChoiceValue(
                            #typefield = 'multichoice_add',
                            #values = ['swap','reiserfs','ext4']),

                            #ChoiceValue(
                            #typefield = 'check',
                            #values = ['on','off'])]
                    #)))
            #group.fields.append(Field(
                    #name = "button_view1",
                    #label = _("Next Step"),
                    #value = 'test_view',
                    #element = "button"))

        if step in [1, None]:
            if not 'view' in locals():
                view = ViewInfo(groups=[])
            else:
                view.groups.append(group)

            group = GroupField(name="Other Settings",nextlabel="Next")
            group.fields = []

            group.fields.append(Field(
                    name = "radiovariable",
                    label = "check city: ",
                    choice = ['Moscow','Piter','New York','London'],
                    type = "str",
                    value = 'London',
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "radio"))
            group.fields.append(Field(
                    name = "radiovariable2",
                    label = "check village: ",
                    choice = ['aaaaaa','bbbb','ccccc','dddddd'],
                    comments = ['a','b','c','d'],
                    type = "str",
                    value = 'bbbb',
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "radio"))
            group.fields.append(Field(
                    name = "comboEdit1",
                    label = "check city number: ",
                    choice = ['M','P','N','L'],
                    comments = ['Moscow','Piter','New York','London'],
                    type = "str",
                    value = 'N',
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "combo"))
            group.fields.append(Field(
                    name = "comboEdit2",
                    label = "check population: ",
                    choice = ['1000','10000','500000','2000000'],
                    type = "str",
                    value = '10000',
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "combo"))
            group.fields.append(Field(
                    name = "multichoice",
                    label = "check population: ",
                    choice = ['1000','10000','500000','2000000','qwe','ert'],
                    type = "str",
                    listvalue = ['1000','ert'],
                    comments = ['Thousand',\
                            'Ten thousand smoothly and is less than a penny'],
                    default = False,
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "multichoice_add"))
            group.fields.append(Field(
                    name = "Partition_table",
                    label = "Mount Points: ",
                    element = "table",
                    type = 'writable',
                    # Table
                    tablevalue = Table(
                    head = ['Partition','Mount Point','Filesystem', \
                                        'Perform format','Label','Size'],
                    body = [['/dev/sda1','swap','swap','off',None,'4G'],\
                            ['/dev/sda2','/','reiserfs','on','CLD','10G'],\
                            ['/dev/sda3','/var/calculate','ext4','off',None,'30G']],
                    values = [ChoiceValue(
                            typefield = 'combo',
                            values = ['/dev/sda1','/dev/sda2','/dev/sda3'],
                            onChanged = ['nothing',None,'get_body','get_body',\
                                         'get_body','get_body']),

                            ChoiceValue(
                            typefield = 'comboEdit',
                            values = ['/','swap','/var/calculate']),

                            ChoiceValue(
                            typefield = 'multichoice_add',
                            values = ['swap','reiserfs','ext4']),

                            ChoiceValue(
                            typefield = 'check',
                            values = ['on','off'])]
                    )))
            if expert:
                group.fields.append(Field(
                        name = "expert_open",
                        #label = "Advanced settings...",
                        type = "label",
                        help = \
                        "you not human? This is a anti-bot test",
                        value = 'open',
                        element = "expert"))
                group.fields.append(Field(
                    name = "multichoice_add",
                    label = "check population: ",
                    choice = ['aa','bb','cc','dd'],
                    comments = ['America','Bosniya','Chine','Denmark'],
                    type = "str",
                    listvalue = ['bb','cc'],
                    default = True,
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "selecttable_add"))
            else:
                group.fields.append(Field(
                        name = "expert_close",
                        #label = "Advanced settings...",
                        type = "label",
                        help = \
                        "you not human? This is a anti-bot test",
                        value = 'close',
                        element = "expert"))
        if step in [2, None]:
            if not 'view' in locals():
                view = ViewInfo(groups=[])
            else:
                view.groups.append(group)

            group = GroupField(name="Gratulations!",last=True)
            group.fields = []

            group.fields.append(Field(
                    name = "final_label",
                    label = "Final step in system install!!! Congratulation!\n"\
                            "Please, select language now!",
                    #value = "border-style: solid; border-width: "
                                                #"2px;border-color: #ff2222;",
                    value = 'border: 0px outset gray;'
                     'border-radius: 6px;'
                     'subcontrol-origin: margin;'
                     'color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,'
                     'stop: 0.1 #bb1111, stop: 0.5 #11bb11, stop: 0.9 #1111bb);'
                     'subcontrol-position: top left; ',
                    element = "label"))
            group.fields.append(Field(
                    name = "comboLang",
                    label = "check language: ",
                    choice = ['Russian','English'],
                    type = "str",
                    value = 'Russian',
                    help = \
                    "you not human? This is a anti-bot test",
                    element = "combo"))
        #if step == None:
            #if not 'view' in locals():
                #view = ViewInfo(groups=[])
            #else:
                #view.groups.append(group)

            #group = GroupField(name="Empty group",last=True)
            #group.fields = []

        view.groups.append(group)

        return view

    #@rpc(Array(String), Array(Array(String)), _returns = Integer)
    #@Dec.check_permissions(["test"])
    #@Dec.console('cl-test')
    #@Dec.gui('Core', 'APITEST', \
            #'/usr/share/wallpapers/Horos/contents/screenshot.png,system-log-out')
    #def apitest ( self, l, t):
        #print '==>', l
        #print '++>', t
