#!/usr/bin/env python

import os
import sys
import errno
import subprocess
import re
from twython import Twython


ApiKey = ''
ApiSecret = ''
AccessToken = ''
AccessTokenSecret = ''
rootdir = os.path.dirname(os.path.realpath(__file__))
cred_file = os.path.join(rootdir, '.auth')
TWITTER_ALLOWED_CHAR = 140

def get_api_token():
    ''' Obtain Twitter app's API token from file .auth
    Returns list
    '''
    f = open(cred_file, 'rb')
    c = f.read()
    t = c.splitlines()
    return t[0:4]

def get_today_str_iso8601():
    ''' Obtain current date in ISO8601 format, without the hyphens,
        e.g., 20170913.
    Returns str
    '''
    d = subprocess.check_output(["date", "+%Y%m%d"])
    d_str = d.translate(None, '\n')
    return d_str

def is_str_prime(d_str):
    '''Returns True if d_str is a prime, False otherwise
    '''
    script = os.path.join(rootdir, 'isprime.sh')
    gpout = subprocess.check_output([script, d_str], shell=False)
    return True if gpout.strip() == '1' else False

def prime_tweet_str(d_str):
    '''
    Returns a string to tweet for prime d_str
    '''
    script = os.path.join(rootdir, 'iswhatprime.sh')
    gpout = subprocess.check_output([script, d_str])
    tweet_str = 'Today ' + gpout
    return tweet_str

def print_base_expo_pair(pair):
    '''Format print (base, exponent) pairs. For example, for ('3' ,'2'),
       it prints '3^2'; for ('3', '1'), it prints '3'.
    Returns string output in specified format
    '''
    if pair[1] == '1':
        outstr = pair[0]
    else:
        outstr = pair[0] + '^' + pair[1]
    return outstr

def composite_tweet_str(d_str):
    '''
    Returns a string to tweet for composite d_str
    '''
    script = os.path.join(rootdir, 'factorit.sh')
    gpout = subprocess.check_output([script, d_str]).strip('\n\[\]Mat')
    gpoutlist = re.split(r'[;,\s]\s*', gpout)
    base_expo_pairs = zip(gpoutlist[0::2], gpoutlist[1::2]) # a list of pairs
    it = iter(base_expo_pairs)
    # Differentiate head and tail, for formatting
    head = it.next()
    tail = list(it)
    tweet_str = 'Today ' + d_str + ' is not a prime\n' \
                + d_str + ' = ' + print_base_expo_pair(head)
    for item in tail:
        tweet_str = tweet_str + ' x ' + print_base_expo_pair(item)
    return tweet_str

def get_tweet_str(d_str):