#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2017 Alexandre Detiste <alexandre@detiste.be>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# You can find the GPL license text on a Debian system under
# /usr/share/common-licenses/GPL-2.

# GDP_UNINSTALLED=1 python3 -m tools.check_gog

import json
import os
import subprocess
from distutils.version import LooseVersion

from game_data_packager.game import load_games
from game_data_packager.gog import GOG

yaml_files = {}
owned_files = []
owned_games = GOG.owned_games()

def decode_filename(archive):
    game = archive[len('setup_')::]
    game = game.rsplit('_', 1)[0].strip()
    version = archive.split('_')[-1][:-4:]
    return(archive, game, version)

print('# Reading data from YAML...')
for name, game in load_games(datadir='out').items():
    game.load_file_data()
    has_tags = has_archive = is_removed = False
    for package in game.packages.values():
        gog = package.gog or game.gog
        if 'removed' in gog:
            is_removed = True
        elif 'url' in gog:
            has_tags = True
    for filename,f in game.files.items():
        if filename.startswith('setup_') and filename.endswith('.exe'):
            has_archive = True
            _, supported, version = decode_filename(filename)
            if '.' not in version:
                # ancient GOG packages
                continue
            if LooseVersion(version) > LooseVersion(yaml_files.get(supported, '0')):
                yaml_files[supported] = version
    if has_tags != has_archive and not is_removed:
        owned = game.gog_download_name(package) in owned_games
        print('GOG metadata not in sync for %s. (has_tags: %s, has_archive: %s, owned: %s)'
              % (name, has_tags, has_archive, owned))

print('# Reading data from LGOGDOWNLOADER...')
cache = os.path.expanduser('~/.cache/lgogdownloader/gamedetails.json')
if not os.path.isfile(cache):
    print("Couldn't locate any game, running 'lgogdownloader --login'")
    subprocess.call(['lgogdownloader', '--login'])
    print("... and now 'lgogdownloader --update-cache'")
    subprocess.call(['lgogdownloader', '--update-cache'])

data = json.load(open(cache, encoding='utf-8'))
for game in data['games']:
    for installer in game['installers']:
        filename = installer['path']
        filename = os.path.basename(filename)
        if filename.startswith('setup_') and filename.endswith('.exe'):
            owned_files.append(decode_filename(filename))

print('# Left join...')
for supported, curr_ver in yaml_files.items():
    for _, to_match, last_ver in owned_files:
        if supported == to_match and last_ver > curr_ver:
            print("%-40s %12s -> %-12s" % (supported, curr_ver, last_ver))
