#! /usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@author: Shreyas <shreyas@ischool.berkeley.edu>

CheckApps
=========
Given an input of apps, check if the app exists
"""

from __future__ import division
from optparse import OptionParser
import time
import requests
import MySQLdb
import pandas as pd
import pandas.io.sql as psql

def getUserInput():
    """
    Get User Input
    """
    optionparser = OptionParser()

    optionparser.add_option('-f', '--file', dest='file')
    optionparser.add_option('-d', '--db', dest='db')
    optionparser.add_option('-s', '--server', dest='server')
    optionparser.add_option('-u', '--username', dest='un')
    optionparser.add_option('-p', '--password', dest='pw')

    (option, args) = optionparser.parse_args()

    #if not option.file:
    #    return optionparser.error('Data File path not provided.\n Usage: --file="path.to.appData"')
    #elif not option


    return {
        'file': option.file,
        'db': option.db,
        'server': option.server,
        'username': option.un,
        'password': option.pw
    }




def checkApps(df):
    """
    Input a dataframe of app ids and check if the apps exist
    in the store
    """

    def getApp(id):
        relaxtime = 1 # 5 s timeout
        time.sleep(relaxtime)

        print 'I\'m checking: ' + id
        r = requests.get(stores['google']+id)

        print id, r.status_code

        return r.status_code

    stores = {
        'google' :'https://play.google.com//store/apps/details?id='
    }

    print df.head(10)
    # df['appId'].apply(getApp)
    df['status'] = df['package'].apply(getApp)

    return df


def getDataframeFromDatabase(host, db, un, pw):
    query = "SELECT package from potential_unfair_apps LIMIT 100;"
    conn = MySQLdb.connect(host = host, user = un, passwd = pw, db = db)
    unfair_apps_df = psql.frame_query(query, conn)
    return unfair_apps_df

def pushDataframeToDatabase(df, host, db, un, pw):
    conn = MySQLdb.connect(host = host, user = un, passwd = pw, db = db)
    df.to_sql(con=conn, name='potential_unfair_apps', if_exists='replace', flavor='mysql')

def main():
    userInput = getUserInput()
    unfair_df = None

    print userInput
    if userInput['file'] != None:
        ptl_unfair_df = pd.read_csv(userInput['file'])
    else:
        ptl_unfair_df = getDataframeFromDatabase(userInput['server'], userInput['db'],
        userInput['username'], userInput['password'])

    unfair_df = checkApps(ptl_unfair_df)
    pushDataframeToDatabase(unfair_df, userInput['server'], userInput['db'],
        userInput['username'], userInput['password'])


if __name__ == '__main__':
    main()

@@ -244,16 +244,32 @@
 rt time%0A
+import datetime%0A
 import r
@@ -341,16 +341,17 @@
 s psql%0A%0A
+%0A
 def getU
@@ -1761,16 +1761,32 @@
 T 100;%22%0A
+    print query%0A
     conn
@@ -1846,24 +1846,26 @@
 w, db = db)%0A
+%0A%0A
     unfair_a
@@ -1903,16 +1903,17 @@
 , conn)%0A
+%0A
     retu
@@ -1978,24 +1978,236 @@
 b, un, pw):%0A
+    timestamp = time.time()%0A    date = datetime.datetime.fromtimestamp(timestamp).strftime('%25Y%25m%25d')%0A    print %22Date: %22, date%0A%0A    db_name = 'potential_unfair_apps_' + date%0A%0A%0A    print %22Database name: %22, db_name%0A
     conn = M
@@ -2300,31 +2300,15 @@
 ame=
-'potential_unfair_apps'
+db_name
 , if

check apps code committed in