"""Entry point module: merge-chunks

Implements the entry-point by using Python or any other languages.
"""

import argparse
import json
import os


def entry_point(system_cache_dir, output_file, chunks_file, chunk_ids,
                proposals=None, localization=None):
    """Method to complete: you have to raise an exception if an error occured
    in the program.

    Given a list of chunk ids, merges all the chunks system output present in
    the list.

    Args:
        system_cache_dir (str): Path to system cache directory
        chunk_file (str):  Path to generate a chunk file, that summarizes all
            the processed videos/activities
        output_file (str): Path to the output file generated
        chunk_ids (:obj:`list`): List of chunk ids
        proposals (str): path to generate a proposals file, that contains the
            system proposals
        localization (str): path to generate a localization file
    """
    out_dict = {}
    out_dict['filesProcessed'] = []
    out_dict['activities'] = []
    out_dict['processingReport'] = {'fileStatuses': {}, 'siteSpecific': {}}
    chunks = {}
    chunks['files'] = []
    chunks['activities'] = []
    chunk_files = []
    if chunk_ids is None:
        # find all available chunks
        for f in os.listdir(system_cache_dir):
            if '_out.json' in f:
                chunk_files.append(os.path.join(system_cache_dir, f))
    else:
        for c in chunk_ids:
            chunk_files.append(
                os.path.join(system_cache_dir, "%s_out.json" % c))
    for f in chunk_files:
        data = json.load(open(f, 'r'))
        out_dict['filesProcessed'].extend(data['filesProcessed'])
        out_dict['activities'].extend(data['activities'])
        out_dict['processingReport']['fileStatuses'].update(data['processingReport']['fileStatuses'])
        chunks['files'].extend(out_dict['filesProcessed'])
        for act in out_dict['activities']:
            if act['activity'] not in chunks['activities']:
                chunks['activities'].append(act['activity'])
    json.dump(out_dict, open(output_file, 'w'))
    json.dump(chunks, open(chunks_file, 'w'))

    # proposals and localization
    if proposals:
        with open(proposals, 'w') as fd:
            fd.write("proposals content")
    if localization:
        with open(localization, 'w') as fd:
            json.dump(out_dict, fd)
