import configparser
import os
from subprocess import getoutput

DEFAULT_SECTION_NAME = 'NONEXIST'


def add_header(opened_file, header):
    """ Return the config file data """
    yield '[{}]\n'.format(header)
    for lne in opened_file:
        yield lne


def read_file(path):
    """ Load the config file """
    config = configparser.ConfigParser()
    config.read_file(add_header(open(path), DEFAULT_SECTION_NAME))

    return dict(config[DEFAULT_SECTION_NAME])


def get_encoding_format(homepath):
    """ Return encoding format from application properties file"""
    path = os.path.join(homepath, 'config', 'application.properties')
    datadict = read_file(path)
    encoding = datadict.get('encodingformat')
    return encoding


def get_encoding_format_from_shell(fle):
    """ Return encoding format of given file from shell script """
    cmd = "file -pi {0}".format(fle)
    output = getoutput(cmd)
    output = output.split('=')
    if len(output) > 1:
        return output[1]
    else:
        return 'utf-8'
