import os


def to_utf8_string(s):
    if isinstance(s, str):
        return s
    if isinstance(s, str):
        return s.encode('utf-8')
    return str(s)


def to_utf8_unicode(s,replace_errors=False):
    if isinstance(s, str):
        return s
    if replace_errors:
        return str(s).decode('utf-8', errors='replace')
    return str(s).decode('utf-8')


def write_error(file, message):
    # expect file as utf8 string
    with open(file, 'wb') as f:
        f.write(message.encode('utf-8', 'backslashreplace') + b'\n')


def os_chown(logger, file):
    # expect file as utf8 string
    try:
        os.chown(file, os.geteuid(), os.getegid())
    except Exception as e:
        logger.warn('could not chown file {0}: {1}'.format(to_utf8_unicode(file),
                                                            to_utf8_unicode(str(e))))


def os_chmod(logger, file, mode):
    # expect file as utf8 string
    try:
        os.chmod(file, mode)
    except Exception as e:
        logger.warn('could not chmode file {0}: {1}'.format(to_utf8_unicode(file),
                                                             to_utf8_unicode(str(e))))


def os_remove(logger, file):
    # expect file as utf8 string
    if not os.path.isfile(file):
        return
    try:
        os.remove(file)
    except Exception as e:
        message = 'could not remove file {0}: {1}'.format(to_utf8_unicode(file),
                                                           to_utf8_unicode(str(e)))
        logger.warn(message)
        write_error(file + '.error.txt', to_utf8_string(message))
