#!/usr/bin/python

# tweets #client.slug, #video, title and url
# shortens the URL and title if needed

# if over 140 char, url is shortened using bity,
# if still over, title is truncated.

import twitter

import urllib.request, urllib.error, urllib.parse
import pprint

import pw  # see pw_samp.py for sample.

from process import process

class tweet(process):

    ready_state = 10

    def shorten(self, url):
        return url # hack because auth broke:
        ## Out[15]: '{\n    "errorCode": 203, \n    "errorMessage": "You must be authenticated to access shorten", \n    "statusCode": "ERROR"\n}'

        d=dict(version='2.0.1',login=pw.bitly['user'], apikey=pw.bitly['password'], longurl=url)
        q = urllib.parse.urlencode(d)
        print(q)
        url = 'http://api.bit.ly/shorten?' + q
        data = eval(urllib.request.urlopen(url).read())
        print(data)
        return list(data['results'].values())[0]['shorturl']

    def mk_tweet(self, prefix, twitter_ids, video_name, authors, video_url):

        #lca2017 My Talk Title - @CarlFK http://youtu.be/123456
        if self.options.verbose:
            print(prefix, twitter_ids, video_name, authors, video_url)

        if twitter_ids:
            message = ' '.join([
                prefix,
                twitter_ids,
                video_name,
                video_url ])
        else:
            message = ' '.join([prefix, video_name, '-',
                authors, video_url ])

        if len(message) > 140:
            message = ' '.join([prefix, twitter_ids, video_name, video_url])
        if len(message) > 140:
            short_url = self.shorten(video_url)
            message = ' '.join([prefix, twitter_ids, video_name, short_url])
        if len(message) > 140:
            video_name = video_name[:140 - len(message) - 3] + '...'
            message = ' '.join([prefix, twitter_ids, video_name, short_url])
        return message

    def tweet_tweet(self, user, tweet):
        if self.options.test:
            print('test mode:')
            print('user:', user)
            print(tweet)
            ret=False
        else:
            print('tweeting:', tweet)
            # print user,password
            t = pw.twit[user]
            api = twitter.Api(consumer_key=t['consumer_key'],
                     consumer_secret=t['consumer_secret'],
                     access_token_key=t['access_key'],
                     access_token_secret=t['access_secret'] )
            if self.options.verbose: print(api.VerifyCredentials())
            status = api.PostUpdate(tweet)
            d=status.AsDict()
            self.last_tweet = d
            self.last_tweet_url = "http://twitter.com/#!/NextDayVideo/status/{}".format(d["id"], )
            print(self.last_tweet_url)
            # pprint.pprint(d)

            ret=True

        return ret

    def process_ep(self, ep):
        show = ep.show
        client = show.client

        # use the username for the client
        user =  client.tweet_id

        url = ep.public_url if ep.public_url \
                else ep.host_url

        prefix = show.client.tweet_prefix

        # remove commas
        if ep.twitter_id is None \
                or not ep.twitter_id:
            twitter_ids = ""
        else:
            twitter_ids = []
            for tid in ep.twitter_id.split(','):
                tid = tid.strip()
                if not tid.startswith('@'):
                    tid = "@" + tid
                twitter_ids.append(tid)
            twitter_ids = ' '.join(twitter_ids)


        tweet = self.mk_tweet(prefix,
                twitter_ids, ep.name, ep.authors, url)

        ret=self.tweet_tweet(user, tweet)
        if ret:
            ep.twitter_url = self.last_tweet_url
            ep.save()

        return ret

    def add_more_options(self, parser):
        parser.add_option('--twitter_user',
           help="account to tweet from if not specified in client.")

    def add_more_option_defaults(self, parser):
        # lag doesn't work right now.
        # parser.set_defaults(lag=120)
        pass

if __name__ == '__main__':
    p=tweet()
    p.main()


@@ -961,16 +961,28 @@
 et(self,
+%0A           
  prefix,
@@ -1025,20 +1025,223 @@
 ideo_url
+, suffix
 ):%0A%0A
+        def j(*args):%0A            print('j:',args)%0A            # remove empty args%0A            args = %5Barg.strip() for arg in args%5B0%5D if arg%5D%0A            s = ' '.join(args)%0A            return s%0A%0A
         
@@ -1359,32 +1359,52 @@
 ix, twitter_ids,
+%0A                   
  video_name, aut
@@ -1418,16 +1418,24 @@
 ideo_url
+, suffix
 )%0A%0A     
@@ -1475,24 +1475,17 @@
 ssage = 
-' '.join
+j
 (%5B%0A     
@@ -1585,17 +1585,40 @@
 ideo_url
- 
+,%0A                suffix
 %5D)%0A     
@@ -1644,32 +1644,25 @@
   message = 
-' '.join
+j
 (%5Bprefix, vi
@@ -1710,16 +1710,24 @@
 ideo_url
+, suffix
  %5D)%0A%0A   
@@ -1772,34 +1772,44 @@
   message = 
-' '.join(%5B
+j(%5B%0A                
 prefix, twit
@@ -1834,24 +1834,32 @@
 e, video_url
+, suffix
 %5D)%0A        i
@@ -1946,34 +1946,44 @@
   message = 
-' '.join(%5B
+j(%5B%0A                
 prefix, twit
@@ -2004,32 +2004,41 @@
 _name, short_url
+, suffix 
 %5D)%0A        if le
@@ -2150,18 +2150,28 @@
 e = 
-' '.join(%5B
+j(%5B%0A                
 pref
@@ -2208,16 +2208,24 @@
 hort_url
+, suffix
 %5D)%0A     
@@ -3403,16 +3403,160 @@
 st_url%0A%0A
+        if  show.client.tweet_prefix.startswith('@'):%0A            prefix = None%0A            suffix = show.client.tweet_prefix%0A        else:%0A    
         
@@ -3588,16 +3588,40 @@
 t_prefix
+%0A            suffix = ''
 %0A%0A      
@@ -4066,16 +4066,33 @@
 k_tweet(
+%0A                
 prefix,%0A
@@ -4144,16 +4144,40 @@
 ors, url
+,%0A                suffix
 )%0A%0A     

move the prefix to the end of the tweet if the prefix begins with @.