#!/usr/bin/python
'''
Created on Nov 25, 2016

@author: chao
'''
import config
import os
from util import file_manager, script_runner, yaml_parser


def install_vundle(plugins=None, plugins_configs_dir=None):

    vundle_yaml = yaml_parser.parse_file(config.VUNDLE_YAML)
    prefix = vundle_yaml.plugin_prefix
    preamble_file = os.path.join(
        config.VUNDLE_DIR, vundle_yaml.plugin_preamble)
    postamble_file = os.path.join(
        config.VUNDLE_DIR, vundle_yaml.plugin_postamble)
    install_file = os.path.join(config.VUNDLE_DIR, vundle_yaml.install_script)

    file_manager.require_file_exists(preamble_file)
    file_manager.require_file_exists(postamble_file)
    file_manager.require_file_exists(install_file)

    file_manager.append_to_file(config.VIMRC_FILE, [preamble_file])

    if plugins is not None:
        with open(config.VIMRC_FILE, 'a+') as vimrc_file:
            for _, plugin in plugins.iteritems():
                vimrc_file.write('\n{0} \'{1}\''.format(prefix, plugin))
            vimrc_file.write('\n')

    file_manager.append_to_file(config.VIMRC_FILE, [postamble_file])

    file_manager.copy_file_to_directory(
        config.VIMRC_FILE, config.USER_HOME_DIR)
    script_runner.run([install_file])

    if plugins is None or plugins_configs_dir is None:
        return

    for plugin_name, _ in plugins.iteritems():
        plugin_config_file = os.path.join(
            plugins_configs_dir, plugin_name + config.CONFIG_FILE_EXT)

        if file_manager.file_exists(plugin_config_file):
            file_manager.append_to_file(
                config.VIMRC_FILE, [plugin_config_file])

    file_manager.copy_file_to_directory(
        config.VIMRC_FILE, config.USER_HOME_DIR)
