1# -*- coding: utf-8 -*-
2
3import zipfile
4import io
5import os
6
7
8SDL2_URL = 'https://github.com/libsdl-org/SDL/releases/download/release-2.26.5/SDL2-devel-2.26.5-VC.zip'  # NOQA
9
10
11def get_path(name: str, p: str) -> str:
12    for file in os.listdir(p):
13        file = os.path.join(p, file)
14
15        if file.endswith(name):
16            return file
17
18        if os.path.isdir(file):
19            if res := get_path(name, file):
20                return res
21
22
23def get_sdl2(path, url=SDL2_URL):
24    import requests  # NOQA
25
26    stream = io.BytesIO()
27
28    with requests.get(url, stream=True) as r:
29        r.raise_for_status()
30
31        content_length = int(r.headers['Content-Length'])
32        chunks = 0
33        # print()
34        # sys.stdout.write('\r' + str(chunks) + '/' + str(content_length))
35        # sys.stdout.flush()
36
37        for chunk in r.iter_content(chunk_size=1024):
38            stream.write(chunk)
39            chunks += len(chunk)
40            # sys.stdout.write('\r' + str(chunks) + '/' + str(content_length))
41            # sys.stdout.flush()
42
43    # print()
44    stream.seek(0)
45    zf = zipfile.ZipFile(stream)
46
47    for z_item in zf.infolist():
48        for ext in ('.h', '.dll', '.lib'):
49            if not z_item.filename.endswith(ext):
50                continue
51
52            zf.extract(z_item, path=path)
53            break
54
55    include_path = get_path('include', path)
56    lib_path = get_path('lib\\x64', path)
57    dll_path = get_path('SDL2.dll', lib_path)
58
59    sdl_include_path = os.path.split(include_path)[0]
60    if not os.path.exists(os.path.join(sdl_include_path, 'SDL2')):
61        os.rename(include_path, os.path.join(sdl_include_path, 'SDL2'))
62
63    zf.close()
64    stream.close()
65
66    return os.path.abspath(sdl_include_path), dll_path
67