import logging


def get_sample2locusId(all_df, has_gene2, meta_ix, dbg_lvl=0):
    """ 
    Args:
        all_df: all.poolcount dataframe
        has_gene2: list of booleans relating to genes with insertions
                    0.1 < f < 0.9
        meta_ix: integer marking where sets begin and not metadata
        
        (Created):
        good_inserts_all_df: data frame which has all poolcount inserts
            that are within 0.1 and 0.9 frac of the gene
        good_locus_ids: a list of all the locus ids which have good values
    Returns:
        sample2locusId is a dict that goes from sample name (str) to a dict of 
          locusId -> num barcodes counted in that locusId
            with only the good gene insertions
    """

    if dbg_lvl > 1:
        logging.info("Starting to get sample2locusId")

    # We get a matrix of sample (col) to genes (rows) with entry being total number
    # of insertions within that gene if the insertions occured within 0.1 and 0.9 f
    good_inserts_all_df = all_df[has_gene2]
    good_locus_ids = good_inserts_all_df['locusId']
    unq_good_loc_id = list(good_locus_ids.unique()) 

    sample2locusId = {}
    # This variable is just to save computation within the upcoming cycles
    col_len = len(good_locus_ids)
    # We iterate over all the sample names (i.e. setname + index) 
    for colname in good_inserts_all_df.columns[meta_ix:]:
        locusId2count = {x:0 for x in unq_good_loc_id}
        current_col = good_inserts_all_df[colname]
        for i in range(col_len):
            locusId2count[good_locus_ids.iat[i]] += int(current_col.iat[i])
        sample2locusId[colname] = locusId2count

    if dbg_lvl > 1:
        logging.info("Finished getting sample2locusId")

    return sample2locusId