#!/usr/bin/env python
# coding=utf-8
#

import base64
import StringIO
import csv
import re

from suds import null as null

from .core import Core


class Translator:

    class CSV:
        DIALECT = 'pyresponse-csv'
        QUOTES = '"'
        ESCAPE = '\\'
        QUOTING = csv.QUOTE_MINIMAL
        SKIP_INITIAL_SPACE = True

    main = None
    factory = None


    def __init__(self, main):
        self.main = main
        self.factory = main.api_client.factory


    def ensuds(self, dictionary):
        """
        Turn a dictionary into a soap structure as defined by the wsdl
        from pyresponse.Api used when instantiating the API wrapper.
        Dictionaries become paintArrays, key, value pairs from the
        dictionary become paintKeyValuePair objects.

        Also manages encoding of keys and values.
        ------------------------------------------------
        @param dictionary                - dictionary of request data
        @return result                   - soap representation of that same data
        """
        if not dictionary:
            return null()
        array = self.factory.create('paintArray')
        for key in dictionary:
            pair = self.factory.create('paintKeyValuePair')
            setattr(pair, 'key', self.x_encode(key, 'ignore'))
            value = getattr(pair, 'value')
            if isinstance(dictionary[key], dict):
                setattr(value, 'arr', self.ensuds(dictionary[key]))
            elif isinstance(dictionary[key], str) or isinstance(dictionary[key], unicode):
                escaped = self.x_encode(dictionary[key], 'xmlcharrefreplace')
                if isinstance(dictionary[key], unicode) and not key.isdigit() and not (key in self.main.encoding_exceptions):
                    (key, escaped) = self.base_encode(getattr(pair, 'key'), escaped)
                    setattr(pair, 'key', key)

                setattr(value, 'str', escaped)
            else:
                setattr(value, 'str', str(dictionary[key]))
            getattr(array, 'pairs').append(pair)
        return array


    def desuds(self, ptarr):