import sys
import time
import datetime

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr

from pyvirtualdisplay import Display

display = Display(visible=0, size=(800, 800))  
display.start()

if __name__ == "__main__":

    #prepare info
    username=sys.argv[1]
    password=sys.argv[2]
    verificationCode="1111"
    area=sys.argv[4]
    email=sys.argv[3]

    #login page and num of seats
    if area=='F1_A':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=8&segment=1404341&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=23:50')
        seatsNum=76
    elif area=='F1_B':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=40&segment=1404354&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=23:50')
        seatsNum=150
    elif area=='F1_digital_reading_area':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=7&segment=1404328&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=23:50')
        seatsNum=24
    elif area=='F1_study_area':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=3&segment=1404315&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=23:50')
        seatsNum=48
    elif area=='F3_foreign_books':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=14&segment=1404198&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=66
    elif area=='F3_newspaper':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=13&segment=1404185&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=68
    elif area=='F4_liberal_art_books_A':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=16&segment=1404224&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=72
    elif area=='F4_liberal_art_books_B':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=17&segment=1404237&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=90
    elif area=='F4_liberal_art_books_C':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=18&segment=1404250&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=98
    elif area=='F5_liberal_art_books':
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=20&segment=1404276&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=154
    else:
        url=('http://seats.lib.ecnu.edu.cn/web/seat3?area=22&segment=1404302&day='+datetime.datetime.now().strftime('%Y-%m-%d')
        +'&startTime='+datetime.datetime.now().strftime('%H:%M')+'&endTime=21:55')
        seatsNum=18

    options = webdriver.ChromeOptions() 
    options.add_argument('--headless') 
    options.add_argument('--disable-gpu') 
    options.add_argument("--no-sandbox") 
    options.add_argument('window-size=1920x3000') 

    #initiate a explorer object
    window=webdriver.Chrome(executable_path ='/usr/bin/chromedriver',options=options)
    window.get(url)
    time.sleep(3)

    #close dialog box
    ActionChains(window).move_by_offset(1, 1).click().perform()


    #login
    window.find_element_by_xpath('/html/body/div[2]/div[1]/ul/li[6]/a').click()

    #input username, password and verification code
    inputUsername=window.find_element_by_name("username")
    inputPassword=window.find_element_by_name("password")
    inputVerificationCode=window.find_element_by_name("verify")
    inputUsername.send_keys(username)
    inputPassword.send_keys(password)
    inputVerificationCode.send_keys(verificationCode)

    #click login button
    window.find_element_by_class_name("ui-dialog-autofocus").click()
    time.sleep(2)
    ActionChains(window).move_by_offset(1, 1).click().perform()
    time.sleep(2)
    ActionChains(window).move_by_offset(1, 1).click().perform()

    #traverse to book a seat
    flag=0
    timenow=datetime.datetime.now()
    while datetime.datetime.now()<(timenow+datetime.timedelta(hours=1)):
        for i in range(1,seatsNum+1):
            xPath=('//*[@id="floor"]/ul/li['+str(i)+']')
            print(xPath)
            if window.find_element_by_xpath(xPath).get_attribute("class")=='seat ava-icon':
                window.find_element_by_xpath(xPath).click()
                time.sleep(3)
                window.find_element_by_class_name('ui-dialog-autofocus').click()
                flag=1
                break
        if flag == 1:
            break
        window.refresh()
        time.sleep(8)

    #notification
    sender='anthonyyoung_ecnu@foxmail.com'
    pwd='cleedzbuzlgrbgba'
    receiver=email
        
    if flag==1:
        msg=MIMEText('您的预定已成功！请到图书馆个人中心查看！','plain','utf-8')
        msg['From']=formataddr(["One-touch Book!",sender])
        msg['To']=formataddr(["",receiver]) 
        msg['Subject']="已为您保留座位"
    else:
        msg=MIMEText('您的预定超时！','plain','utf-8')
        msg['From']=formataddr(["One-touch Book!",sender])
        msg['To']=formataddr(["",receiver]) 
        msg['Subject']="预定失败"
    server=smtplib.SMTP_SSL("smtp.qq.com", 465) 
    server.login(sender, pwd)
    server.sendmail(sender,[receiver,],msg.as_string())
    server.quit()