#!/usr/bin/env python

# Copyright 2015 Netherlands eScience Center <info@esciencecenter.nl>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from corpora.scikit import ScikitLda

import os
import numpy
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import pairwise_distances
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.manifold import MDS, TSNE
import gensim
from numpy import argsort
from wordcloud import WordCloud
import math
import argparse


class clustering:

    def __init__(self, dirname, dictionary):
        # initialize object
        self.dirname = dirname
        self.dictionary = dictionary
        self.load_topics(self.dirname)
        self.dic = gensim.corpora.Dictionary.load(self.dictionary)
        self.find_distance_matrix(metric='cosine')
        self.angularize()  # angularize distance matrix
        self.pos = self.data_embedding(type='TSNE')

        # self.main()

    def return_n_words(self, dic, topic, n_words):
        '''
        return the top n words in the topic
        '''
        aa = [(dic[idx], topic[idx]) for idx in argsort(topic)[-n_words:]]
        return dict(aa)

    def create_scatter(self, size=100, filename=None):
        '''
        create scatter plot of the clusters found
        '''
        num_k = len(set(self.k_fit))  # number of kernels
        plt.figure(figsize=(15, 15))
        x = numpy.arange(num_k)
        # TODO: yys is unused!!
        yys = [i + x + (i * x)**2 for i in range(num_k)]
        colors = cm.nipy_spectral(numpy.linspace(0, 1, num_k))
        for idx in range(0, num_k):
            plt.scatter(self.pos[numpy.where(self.k_fit == idx), 0], self.pos[numpy.where(self.k_fit == idx), 1],
                        s=100, label=str(idx), c=colors[idx])
        plt.legend()
        if filename == None:
            plt.show()
        else:
            plt.savefig(filename, dpi=300)
        plt.close()

    def create_wordcloud(self, filename=None):
        '''
        create a wordcloud of the top words in a cluster