# Map spreadsheet manipulation

import re

import Parser
import strings
import util

##### Metadata

def col_info(col_name, require_root=False):
    '''@return tuple (label, root, prefixes)'''
    def syntax_err(): raise Parser.SyntaxError('Column name must have '
        'syntax "datasrc[format,...]:root" (formats optional): '+col_name)
    
    match = re.match(r'^([^\[:]*)(?:\[([^\]]*?)\])?(?::(.*))?$', col_name)
    if not match: syntax_err()
    label, prefixes, root = match.groups()
    if require_root and root == None: syntax_err()
    return label, root, strings.split(',', util.coalesce(prefixes, ''))

##### Combinability

def col_formats(col_name):
    label, root, prefixes = col_info(col_name)
    return [label]+prefixes

def cols_combinable(*col_names):
    return strings.overlaps(*[','.join(col_formats(c)) for c in col_names])

def combinable(*headers): return cols_combinable(*[h[0] for h in headers])

def strip_root(root): return re.sub(r':\[[^\]]*?\]', r'', root)

def stripped_root(col_name):
    '''@return NamedTuple (labels, root)'''
    return util.do_ignore_none(strip_root, col_info(col_name)[1])

def cols_root_combinable(*col_names):
    roots = map(stripped_root, col_names)
    return roots[0] == None or roots[1] == None or roots[0] == roots[1]

def cols_fully_combinable(*col_names):
    return cols_combinable(*col_names) and cols_root_combinable(*col_names)

def join_combinable(*headers):
    return cols_fully_combinable(headers[0][1], headers[1][0])

##### Merging

def is_nonexplicit_empty_mapping(row):
    return reduce(util.and_, (v == '' for v in row[1:]))

def merge_values(*vals):
    new = []
    for val in vals:
        if val != '' and val not in new: new.append(val)
    return '; '.join(new)

def merge_rows(*rows):
    '''e.g. ['a','b'] + ['','y','z'] = ['a','b; y','z']'''
    def get(row, i):
        try: return row[i]
        except IndexError: return ''
    return [merge_values(*[get(row, i) for row in rows])
        for i in xrange(max(map(len, rows)))]

def merge_mapping_cols(in_, out, prefer=None):
    '''@param prefer None = [in_[0], out[1]]; 0 = in_; 1 = out'''
    if prefer == None: return [in_[0], out[1]]
    elif prefer == 0: return in_
    elif prefer == 1: return out
    else: raise Parser.SyntaxError('Invalid prefer: '+repr(prefer))

def merge_mappings(in_, out, **kw_args):
    '''e.g. ['in','join','in_comments'] + ['join','out','out_comments'] =
    ['in','out','in_comments; out_comments']'''
    return (merge_mapping_cols(in_[:2], out[:2], **kw_args)
        + merge_rows(in_[2:], out[2:]))

def merge_headers(in_, out, **kw_args):
    out_cols = [in_[1], out[1]]
    if cols_fully_combinable(*out_cols): out[1] = util.longest(*out_cols)
    return merge_mappings(in_, out, **kw_args)
