import os
import json
import codecs
from optparse import OptionParser

from collections import defaultdict

import numpy as np
import pandas as pd

from ..util import file_handling as fh
from ..util import dirs


def get_labels(label_file, target, weight_col=None, combine_by_voting=False):

    input_dir = dirs.data_raw_labels_dir
    input_filename = fh.make_filename(input_dir, fh.get_basename_wo_ext(label_file), 'csv')
    label_df = pd.read_csv(input_filename, header=0, index_col=0)
    n, p = label_df.shape
    if weight_col >= 0:
        col = label_df.columns[int(weight_col)]
        weights = label_df[col].ravel()
    else:
        weights = None

    if type(target) == int:
        label_name = label_df.columns[target]
    else:
        label_name = target

    true_dict = defaultdict(set)
    for index, item in enumerate(label_df.index.tolist()):
        true_dict[item].add(label_df.ix[index, target])
    unanimous_pairs = {i: v.pop() for i, v in true_dict.items() if len(v) == 1}

    if combine_by_voting:
        label_df['temp'] = 1
        grouped = label_df.groupby(label_df.index).sum()
        counts = grouped[label_name].ravel()
        totals = grouped['temp'].ravel()
        # using this list comprehension, because np.round(0.5) := 0
        grouped['labels'] = [int(round(t)) for t in counts/totals]
        labels = grouped['labels'].ravel()
        index = grouped.index.tolist()
        weights = np.ones(len(index))
    else:
        labels = label_df[label_name].ravel()
        index = label_df.index.tolist()

    return index, label_name, labels, weights, unanimous_pairs




