#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab

# 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.

"""
General text functions. You may import this instead of the stock
"string" module in most cases.

"""

from __future__ import absolute_import
from __future__ import print_function

import re
import binascii

from pycopia.aid import removedups
from pycopia.ascii import *

def cut_string(s, maxlen=800):
    """Cuts a long string, returning the head and tail combined, with the
middle missing. """
    if len(s) <= maxlen:
        return s
    halflen = (min(maxlen, len(s))/2)-6
    return s[:halflen]+"[...snip...]"+s[-halflen:]
snip_string = cut_string # alias

def random_string(size):
    """Return a string of length <size> with random alphanumeric
characters in it."""
    import random
    rng = random.random
    lseq = len(alphanumeric)
    x = list(range(size))
    for i in x:
        x[i] = alphanumeric[int(rng() * lseq)]
    return "".join(x)

def crange(start, fin):
    """like range(), but for characters."""
    for i in range(start, fin+1):
        yield chr(i)

def maketrans(s, d):
    """maketrans(frm, to) -> string
    Return a translation table (a string of 256 bytes long). """
    tbl = list(range(256))
    for src, dest in zip(s, d):
        tbl[ord(src)] = ord(dest)
    return "".join([chr(b) for b in tbl])

tbl = ["_"]*256
for c in alphanumeric:
    tbl[ord(c)] = c
_IDENTTABLE = "".join(tbl)
del tbl, c

# build keyword map
import keyword
_KEYWORDS = {}
for kw in keyword.kwlist:
    _KEYWORDS[kw] = kw + "_"
del kw, keyword

def identifier(tag):
    """Return a valid Python identifier given an arbitrary string."""
    tag = str(tag)
    return tag.translate(_IDENTTABLE).capitalize()

def keyword_identifier(name):
    """Return a valid Python keyword identifier given an arbitrary string."""
    ident = name.translate(_IDENTTABLE)
    return _KEYWORDS.get(ident, ident)

# creating a new translation table all the time is annoying. This makes a
# default one automatically.
def translate(string, frm, to, table=None, deletechars=None):
    """Translate a string using table (one will be built if not supplied).
    First remove 'deletechars' characters from 'string', then translate the
    'from' characters to the 'to' characters."""
    table = table or maketrans(frm, to)
    return string.translate(table, deletechars)

# text filters follow
def grep(patt, *args):
    """grep(pattern, objects...)
returns a list of matches given an object, which should usually be a list of
strings, but could be a single string.  """