# -*- 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
import calculate.contrib
from suds import MethodNotFound


from calculate.lib.utils import ip as ip
_ = lambda x: x
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_core3', sys.modules[__name__])

def getIpLocal():
    for interface in ip.getInterfaces():
        return ip.getIp(interface)
    else:
        return ""

def getHwAddr():
    """ get MAC adress for interface """
    for interface in ip.getInterfaces():
        return ip.getMac(interface)
    else:
        return ""

def get_sid(sid_file):
    if not os.path.exists(sid_file):
        with open(sid_file, 'w') as fi:
            fi.write('0')
        sid = 0
    else:
        with open(sid_file, 'r') as fi:
            sid = fi.read()
    return sid


def clear():
    """ delete caching suds file """
    import glob

    for filename in glob.glob("/tmp/suds/suds-*"):
        try:
            os.unlink(filename)
        except OSError as e:
            print(str(e))
            print(_("Failed to clear the cache! "))
            return 1


def get_ip_mac_type(client_type=None):
    results = [getIpLocal(), getHwAddr()]
    if client_type:
        results.append(client_type)
    else:
        results.append('console')
    return results


def create_obj(client, method_name):
    """ create object indispensable for transfer to the server function """
    sd_item = 0
    num_port = 0
    operation_from_port = 0
    inf_param = 1
    param_type = 0
    ns_name = 0
    ns_type = 1
    param = 1
    pref = ""

    sd = client.sd[sd_item]

    # get parameter type
    operation = sd.ports[num_port][operation_from_port]

    info = operation.methods.get(method_name)
    if not info:
        raise MethodNotFound(method_name)
    type_op = info.binding.input.param_defs(info)[param][inf_param]
    str_type = type_op.type[param_type]

    # get prefix
    str_ns = type_op.type[ns_type]
    nsprefix = sd.prefixes

    # Find a match prefix
    for pref_num in range(0, len(nsprefix)):
        if str_ns == sd.prefixes[pref_num][ns_type]:
            pref = sd.prefixes[pref_num][ns_name]
    # Combine in a type
    if not pref:
        pref = sd.getprefix(str_ns)
    for_factory = pref + ":" + str_type

    return client.factory.create(for_factory)


def listToArray(client, _list, _type='string'):
    array = client.factory.create('%sArray' % _type)
    for i in _list:
        array['%s' % _type].append(i)
    return array


def listToArrayArray(client, _list, _type='string'):
    array_array = client.factory.create('%sArrayArray' % _type)
    for i in _list:
        array = client.factory.create('%sArray' % _type)
        for j in i:
            array[_type].append(j)
        array_array['%sArray' % _type].append(array)
    return array_array


class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args:  # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

