from __future__ import absolute_import, print_function, division

import os
import re
import time
import platform
import subprocess
import ConfigParser

from lwp.exceptions import ContainerNotExists, LxcConfigFileNotComplete
from lwp.lxclite import exists, stopped
from lwp.lxclite import lxcdir
from lwp.utils import cgroup_ext


class FakeSection(object):
    def __init__(self, fp):
        self.fp = fp
        self.sechead = '[DEFAULT]\n'

    def readline(self):
        if self.sechead:
            try:
                return self.sechead
            finally:
                self.sechead = None
        else:
            return self.fp.readline()


def del_section(filename=None):
    if filename:
        with open(filename, 'r') as f:
            read = f.readlines()
        i = 0
        while i < len(read):
            if '[DEFAULT]' in read[i]:
                del read[i]
                break
        with open(filename, 'w') as f:
            f.writelines(read)


def file_exist(filename):
    """
    checks if a given file exist or not
    """
    try:
        with open(filename) as f:
            f.close()
            return True
    except IOError:
        return False


def memory_usage(name):
    """
    returns memory usage in MB
    """
    if not exists(name):
        raise ContainerNotExists("The container (%s) does not exist!" % name)
    if name in stopped():
        return 0
    cmd = ['lxc-cgroup -n %s memory.usage_in_bytes' % name]
    try:
        out = subprocess.check_output(cmd, shell=True).splitlines()
    except subprocess.CalledProcessError:
        return 0
    return int(int(out[0]) / 1024 / 1024)


def host_memory_usage():
    """
    returns a dict of host memory usage values
                    {'percent': int((used/total)*100),
                    'percent_cached':int((cached/total)*100),
                    'used': int(used/1024),
                    'total': int(total/1024)}
    """
    total, free, buffers, cached = 0, 0, 0, 0
    with open('/proc/meminfo') as out:
        for line in out:
            parts = line.split()
            key = parts[0]
            value = parts[1]
            if key == 'MemTotal:':
                total = float(value)
            if key == 'MemFree:':
                free = float(value)
            if key == 'Buffers:':
                buffers = float(value)
            if key == 'Cached:':
                cached = float(value)
    used = (total - (free + buffers + cached))
    return {'percent': int((used / total) * 100),
            'percent_cached': int((cached / total) * 100),
            'used': int(used / 1024),
            'total': int(total / 1024)}


def host_cpu_percent():
    """
    returns CPU usage in percent
    """