"""
 *
 * This file is part of rasdaman community.
 *
 * Rasdaman community is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Rasdaman community is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU  General Public License for more details.
 *
 * You should have received a copy of the GNU  General Public License
 * along with rasdaman community.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright 2003 - 2016 Peter Baumann / rasdaman GmbH.
 *
 * For more information please see <http://www.rasdaman.org>
 * or contact Peter Baumann via <baumann@rasdaman.com>.
 *
"""
# make sure all string literals are Unicode
from __future__ import unicode_literals
import uuid
import time
import datetime

def stringify(thing):
    """
    Adds quotes to the given parameter and casts to string if the object is not a string
    :param str thing: the thing to stringify
    :rtype: str
    """
    return '"' + str(thing) + '"'


def is_number(value):
    """
    Check if string value is a number (e.g: -5, 2, 3.5, 1e+5)
    :param string value: the value needs to check
    :return boolean:
    """
    try:
        float(value)
        return True
    except ValueError:
        return False


def generate_password():
    """
    Generates a password using a hex-ed uuid4 generated by python.
    :rtype: str
    """
    return uuid.uuid4().hex


def strip_whitespace(s):
    """
    Strip all whitespace from a string s
    :param str|bytes s: input string
    :rtype: str
    """
    if type(s) != bytes:
        return s.strip(" \t\n\r")
    else:
        return s.decode("utf-8").strip(" \t\n\r")


def strip_trailing_zeros(number_str):
    """
    Strip any zeros from number in string (e.g: 111.0 -> 111)
    """
    return number_str.rstrip('0').rstrip('.')


def fix_newlines(s):
    """
    Fix the literal \n characters to proper new lines
    :param str s: input string
    :rtype: str
    """
    return s.replace('\\n', '\n')


def replace_in_list(l, old, new):
    """
    Remove the old item from list (if it exists), and append the new item
    """
    if old in l:
        l.remove(old)
    l.append(new)
    return l


def get_timestamp(t=None):
    """
    Get a current timestamp formatted as %Y-%m-%d %H:%M:%S
    :param time t: input time
    :rtype: str
    """
    start = t
    if t is None:
        start = time.time()
    return datetime.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S')


def get_file_timestamp(t=None):
    """
    Get a current timestamp formatted file-friendly as %Y-%m-%d_%H-%M-%S
    :param time t: input time
    :rtype: str
    """
    start = t
    if t is None:
        start = time.time()
    return datetime.datetime.fromtimestamp(start).strftime('%Y-%m-%d_%H-%M-%S')

def binary_to_string(msg):
    if msg is not None:
        try:
            if type(msg) == bytes:
                return msg.decode("utf-8", "replace")
            else:
                return msg
        except Exception as e:
            return "Failed to serialize to UTF-8: " + str(e)
    else:
        return ""
