import urllib2
import urllib
import cookielib
import re
import sys
from datetime import datetime, timedelta

#Ganti username dengan username anda
USERNAME = "KLIKBCAUSERNAME"
#Ganti pin dengan pin anda
PIN = "999999"

#Please do not edit below this line or you will be eaten by the dragons
#-----------------------------------------------------------------------

cookie_handler = urllib2.HTTPCookieProcessor()
https_handler = urllib2.HTTPSHandler(debuglevel=0)
urllib2.install_opener(urllib2.build_opener(cookie_handler,https_handler))

def get_ip(result):
    """Retrieve IP from BCA Index
    """
    return re.search('<input type="hidden" name="value\(user_ip\)".*?value="(.*?)">', result).group(1)

def login_success(result):
    """Check for login success
    """
    match = re.search('<frame src="authentication.do\?value\(actions\)=welcome" name="atm">', result)
    if match:
        return True
    match = re.search('Anda dapat melakukan login kembali setelah 10 menit', result)
    if match:
        print match.group(0)
    return False

def do_logout():
    """Do logout
    If we not do this, BCA will block our account for about 10 minutes
    """
    logout_url = "https://ibank.klikbca.com/authentication.do?value(actions)=logout"
    resp = urllib2.urlopen(logout_url, urllib.urlencode({}))
    print "Logout success"

def do_login():
    """Do login
    """
    url = "https://ibank.klikbca.com/"
    resp = urllib2.urlopen(url)
    result = resp.read()
    ip_addr = get_ip(result)
    print "ip address: %s" % ip_addr
    
    login_url = "https://ibank.klikbca.com/authentication.do"
    post_data = {
        "value(actions)":"login",
        "value(user_id)":USERNAME,
        "value(user_ip)":ip_addr,
        "value(pswd)":PIN,
        "value(Submit)":"LOGIN"
    }
    resp = urllib2.urlopen(login_url, urllib.urlencode(post_data))
    result = resp.read()
    if not login_success(result):
        raise ValueError("Login failed")

def do_fetch_transaction():
    """Fetch transaction as HTML
    """
    print "Login success, fetching transactions..."
    accstmt_url = "https://ibank.klikbca.com/accountstmt.do?value(actions)=acctstmtview"
    today = datetime.today()
    delta = timedelta(30)
    last_month = today - delta
    post_data = {
        "value(D1)":"0",
        "value(startDt)":str(last_month.day),
        "value(startMt)":str(last_month.month),
        "value(startYr)":str(last_month.year),
        "value(endDt)":str(today.day),
        "value(endMt)":str(today.month),
        "value(endYr)":str(today.year),
        "value(submit1)":"Lihat Mutasi Rekening"
    }
    
    resp = urllib2.urlopen(accstmt_url, urllib.urlencode(post_data))
    result = resp.read()
    result = re.compile('<script.*?>(.*?)</script>', re.S).sub('', result)
    
    filename = "klikbca-%s%s%s.html" % (today.year,today.month,today.day)
    f = open(filename, 'wb')
    f.write(result)
    f.close()
    print "saved to: %s" % filename


def do_fetch_csv():
    """Fetch transaction as CSV
    """
    print "Login success, fetching transactions..."
    
    #Dummy request for setting BCA sessions, stmtdownload.do won't work without this
    url = "https://ibank.klikbca.com/accountstmt.do?value(actions)=acct_stmt"
    resp = urllib2.urlopen(url, "")
    result = resp.read()
    
    #The real fetch
    accstmt_url = "https://ibank.klikbca.com/stmtdownload.do?value(actions)=account_statement"
    today = datetime.today()
    delta = timedelta(30)
    last_month = today - delta
    post_data = {
        "value(D1)":"0",
        "value(startDt)":str(last_month.day),
        "value(startMt)":str(last_month.month),
        "value(startYr)":str(last_month.year),
        "value(endDt)":str(today.day),
        "value(endMt)":str(today.month),
        "value(endYr)":str(today.year),
        "value(submit2)":"Download Mutasi"
    }

    resp = urllib2.urlopen(accstmt_url, urllib.urlencode(post_data))
    result = resp.read()
    filename = "klikbca-%s%s%s.html" % (today.year,today.month,today.day)
    head = resp.info().getheader('Content-Disposition')
    if head:
        key = 'filename='
        index = head.rfind(key)
        if index > 0:
            filename = head[index + len(key):len(head)-1].lower()
    f = open(filename, 'wb')
    f.write(result)
    f.close()
    print "saved to: %s" % filename

if __name__ == "__main__":
    try:
        do_login()
        #do_fetch_transaction()
        do_fetch_csv()
        do_logout()
    except urllib2.HTTPError, e:
        print "error: %s" % e.code
        do_logout()
    except urllib2.URLError, e:
        print "error: %s" % e.reason
        do_logout()
    except:
        print "error: %s" % str(sys.exc_info()[1])
        do_logout()
    
    
