#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2018 Alexandre Detiste <alexandre@detiste.be>
# SPDX-License-Identifier: GPL-2.0-or-later

# Usage:
# curl -s -D headers.html http://wiki.scummvm.org/index.php/Where_to_get_the_games > scummvm.html
# _build/run-tool-uninstalled tools/check_scummvm.py

import os
import re
from bs4 import BeautifulSoup

from game_data_packager.game import load_games

games = {}
print('# Reading data from YAML...')

for name, game in load_games(
    datadir=os.environ.get('GDP_BUILDDIR', 'out')
).items():
    game.load_file_data()
    if game.wikibase != 'http://wiki.scummvm.org/index.php/':
         continue
    assert game.wiki, name

    gog_id = None
    steam_id = None
    for package in game.packages.values():
        gog = package.gog or game.gog
        steam = package.steam or game.steam
        if 'game' in gog:
            gog_id = gog['game']
        elif 'url' in gog:
            gog_id = gog['url']
        if 'id' in steam:
            steam_id = steam['id']

    games[game.wiki] = (gog_id, steam_id)

print('# Reading data from ScummVM wiki...')

# curl -s -D headers.html http://wiki.scummvm.org/index.php/Where_to_get_the_games > scummvm.html

soup = BeautifulSoup(open("scummvm.html"), "html.parser")

downloads = dict()
for table in soup.find_all('table', {'border':'1', 'width':'100%'}):
    print('## ' +table.find_previous('span').text)
    for row in table.find_all('tr'):
        game = None
        for link in row.find_all('a'):
            url = link['href']
            if url == 'http://www.scummvm.org/games/':
                continue
            if 'cdaccess.com/' in url:
                continue

            m = re.search('/index.php/(.*?)$', url)
            if m:
                game = m.group(1)
                downloads.setdefault(game, dict())
                continue

            m = re.search('http://gog.com/game/(.*?)\?pp\=22d200f8670dbdb3e253a90eee5098477c95c23d', url)
            if m:
                downloads[game]['gog'] = m.group(1)
                continue

            m = re.search('http://store.steampowered.com/app/(.*?)$', url)
            if m:
                downloads[game]['steam'] = int(m.group(1))
                continue

            print(game, url)

print('# Join...')
for game, shops in sorted(games.items()):
    shop = shops[0]
    new_shop = downloads.get(game,dict()).get('gog')
    if shop != new_shop:
        print("%-70s" % game, shop, new_shop)

    shop = shops[1]
    new_shop = downloads.get(game,dict()).get('steam')
    if shop != new_shop:
        print("%-70s" % game, shop, new_shop)

