# Script to scrape all levels.
# geckodriver needs to be downloaded, and be in PATH

from selenium import webdriver
from time import sleep
import json
import os

import constants

current_dir = os.getcwd()
data_dir = 'data'.join(current_dir.rsplit('code', 1))
level_dir = os.path.join(data_dir, 'levels')

if not os.path.exists(level_dir):
    os.makedirs(level_dir)


def login(driver):
    username = driver.find_element_by_name('login')
    password = driver.find_element_by_name('password')

    username.send_keys(constants.LOGIN_USER)
    password.send_keys(constants.LOGIN_PASSWD)

    driver.find_element_by_css_selector('input.login_button').click()
    sleep(0.25)

def parse_level(driver):
    level = {}
    level['hasTopWall'] = driver.execute_script('return hasTopWall;')
    level['hasRightWall'] = driver.execute_script('return hasRightWall;')
    level['hasBottomWall'] = driver.execute_script('return hasBottomWall;')
    level['hasLeftWall'] = driver.execute_script('return hasLeftWall;')
    level['isCheckpoint'] = driver.execute_script('return isCheckpoint;')
    level['ball_row'] = driver.execute_script('return row;')
    level['ball_col'] = driver.execute_script('return col;')
    level['width'] = driver.execute_script('return width;')
    level['height'] = driver.execute_script('return height;')
    return level

def save_level(level, level_name):
    level_text = json.dumps(level, sort_keys=True)
    level_name = os.path.join(level_dir, level_name)
    with open(level_name, 'w') as out:
        out.write(level_text)

driver = webdriver.Firefox()
driver.get(constants.LEVEL_LIST_URL)

sleep(0.25)

login(driver)

levels_ids = []

with open(os.path.join(data_dir, constants.USER_TIME_FILE), 'r') as user_time:
    first_line = user_time.readline().strip()
    levels_ids = first_line.split(',')[1:]

for level_id in levels_ids:
    level_name = constants.get_level_name(level_id)
    print('scraping', level_name)
    level_url = constants.get_level_url(level_id)

    driver.get(level_url)
    sleep(0.25)
    level = parse_level(driver)
    save_level(level, level_name)

driver.quit()
