import re
import pickle
import matplotlib.pyplot as plt
import itertools
import numpy as np

def FindUrls(message):
    return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message)

def PickleMe(object, name, path = './pickles/'):
    print 'saving ' + name
    with open(path + name, 'wb') as handle:
        pickle.dump(object, handle)
    print 'saving finished..'
        
def DepickleMe(name, path = './pickles/', quiet = False):
    if not quiet:
        print 'loading ' + name
    ret = pickle.load(open(path + name, "rb" ) )
    if not quiet:
        print 'loaded ..'
        
    return ret

def FindBugByID(data, bug_id):
    index = -1
    bd = long(bug_id)    
    for row in data:
        index += 1            
        if len(row) > 1:
            if row[1] == bd:
                return row, index
                 
    return None, None   
        
def FindDeveloperByID(data, dev_id):
    index = -1
    for row in data:
        index += 1
        if row[0] == dev_id:
            return row, index
        
def FindIndexByBugID(bugs_, bug_id):
    index = -1
    ret = -1
    for key, item in bugs_.iteritems():    
        index += 1    
        bug = key[: key.find('$')]    
        if bug == bug_id:
            ret = index
            break
        
    return ret
            
            
        
def CleanStr(st):
    st = st.replace('.', '')
    st = st.replace('_', '')
    st = st.replace(' ', '')
    return st.lower()

def plot_confusion_matrix_simple(hnd, cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    
    ax = hnd.add_subplot(111)
    cax = ax.matshow(cm)
    #plt.title('Confusion matrix of the classifier')
    #hnd.colorbar(cax)
    plt.colorbar()
    ax.set_xticklabels([''] + classes)
    ax.set_yticklabels([''] + classes)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()
    
def plot_confusion_matrix(hnd, cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    
    ax = plt.imshow(cm, interpolation='none', cmap=cmap)
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    _, lbs = plt.xticks(tick_marks, classes, rotation=270)
    [t.set_color('red') for t in lbs]
    _, lbs = plt.yticks(tick_marks, classes)
    [t.set_color('blue') for t in lbs]
    
    #[t.set_color('red') for t in ax.xaxis.get_ticklabels()]
    #[t.set_color('blue') for t in ax.yaxis.get_ticklabels()]
    
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)
    PickleMe(cm, 'confusion_matrix_busy.pkl')

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        if normalize:
            plt.text(j, i, '%0.1f' % (cm[i, j]),
                horizontalalignment="center",
                color="white" if cm[i, j] > thresh else "black",
                alpha=0.05 if cm[i,j] == 0 else 0.6)
        else:
            plt.text(j, i, cm[i, j],
                horizontalalignment="center",
                color="white" if cm[i, j] > thresh else "black",
                alpha=0.05 if cm[i,j] == 0 else 0.6)

    #plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()

    
    
    
    
    
    
