""" Basic Clousmesh finctions.

.. role:: strikethrough

This file contains some very basic utility functions that must not
need any import from cloudmesh. That is no statement such as

* :strikethrough:`import cloudmesh`

must occur in the list of import. If functions are needed hat need to
be used they must be decleard without dependencies in::

  import cloudmesh.util

The reasonong is that during th einitialization where cloudmesh is not
yet installed, the __init__ function for cloudmesh may include some
configuration files that are not yet present at the tome of the first
instalation.
"""
from __future__ import print_function
from cloudmesh_base.util import path_expand
import inspect
import os
import sys
import uuid
import functools
# import warnings
import string
import random
from cloudmesh_base.util import banner
from cloudmesh_base.util import grep
from cloudmesh_base.locations import config_file

try:
    from progress.bar import Bar
except:
    try:
        os.system("pip install progress")
        from progress.bar import Bar
    except Exception, e:
        print("ERROR: can not install progress")
        print(e)
        print(70 * "=")
        print("please make sure that a virtualenv and pip are installed")
        sys.exit()

class PROGRESS(object):

    defined = False
    bar = None

    @classmethod
    def set(cls, msg, limit):
        if not cls.defined:
            cls.bar = Bar(msg, max=limit)
            cls.defined = True

    @classmethod
    def next(cls):
        cls.bar.next()

    @classmethod
    def finish(cls):
        cls.bar.finish()

    @classmethod
    def __del__(cls):
        cls.bar.finish()

def cat(filename):
    """prints the contents of a file with the given name.

    :param filename: name of the file, which can include ~ and $
                     environment variables
    :type: string
    """
    location = path_expand(filename)
    banner(filename)
    with open(location, 'r') as f:
        print(f.read())


def not_implemented():
    """prins simply an error that this is not implemented. This can be
    used when you protortype things."""

    print("ERROR: not yet implemented")


def check_file_for_tabs(filename, verbose=True):
    """identifies if the file contains tabs and returns True if it
    does. It also prints the location of the lines and columns. If
    verbose is set to False, the location is not printed.

    :param filename: the filename
    :rtype: True if there are tabs in the file
    """
    file_contains_tabs = False
    with file(filename) as f:
        lines = f.read().split("\n")

    line_no = 1
    for line in lines:
        if "\t" in line:
            file_contains_tabs = True
            location = [
                i for i in range(len(line)) if line.startswith('\t', i)]
            if verbose:
                print("Tab found in line", line_no, "and column(s)", location)
        line_no = line_no + 1