r"""SentimentTransformer uses TextBlob.sentiment to generate sentiment
    based feature vectors (either lexical or naive bayes).

:Author:
    Matthias Manhertz
:Copyright:
    (c) Matthias Manhertz 2015
:Licence:
    MIT
"""

from .feature_transformer import FeatureTransformer
from .combine import combine_sentiments
from time import time
import numpy as np


class SentimentTransformer(FeatureTransformer):
    r"""Transforms json files into count sentiment features

        The SentimentTransformer makes it easy to transform .json files
        containing twitter-data (like the ones generated by
        twistml's filtering and / or preprocessing steps) sentiment
        vector features.

        <Notes>

        References
        ----------

        Example Usage
        -------------
        ::
            import twistml as tml

            filepaths = tml.find_files('c:/data/')
            snt = tml.features.SentimentTransformer(analyzer='pattern')
            features = snt.transform(filepaths)

    """  # NOQA

    def __init__(self, analyzer='pattern',
                 timeformat="%a %b %d %H:%M:%S +0000 %Y"):
        r"""Initialize the SentimentTransformer

        Parameters
        ----------


        References
        ----------

        """  # NOQA

        self.analyzer = analyzer
        self.timeformat = timeformat

    def transform(self, filepaths):
        r"""Transforms twitter data in files into a dict mapping
            datestamps to sentiment vectors.

            Parameters
            ----------
            filepaths : list(str)
                A list of files that contain tweets in the typical
                format (dict[str, str]) as generated by the filtering
                and / or preprocessing functions in twistml.

            Returns
            -------
            daily_sents : dict[datetime, ndarray]
                A dict mapping datestamps to sentiment vectors in
                numpy ndarray format.

        """

        combined = combine_sentiments(filepaths, self.analyzer,
                                      self.timeformat)

        t0 = time()
        print "Vectorizing...",
        daily_sents = {}
        for date, sents in combined.iteritems():
            # construct the feature vectors by calculating several metrics
            metrics = []
            # metric 1: daily mean of the sentiment scores
            metrics.extend(np.mean(sents, axis=0))
            # metric 2: daily median of the sentiment score
            metrics.extend(np.median(sents, axis=0))

            daily_sents[date] = np.reshape(np.asarray(metrics), (1, -1))

        print " done in  {0:.1f}min.".format((time()-t0)/60)

        return daily_sents

    pass
