# python3

import threading
from threading import Thread

from flags import save_flag, show, main, get_flag


class MyThread(Thread):

    def __init__(self, func, args, name=""):
        super(MyThread, self).__init__()
        self.name = name
        self.func = func
        self.args = args

    def getResult(self):
        return self.res

    def run(self):
        # 创建新线程的时候，Thread 对象会调用我们的 ThreadFunc 对象，这时会用到一个特殊函数 __call__()。
        self.res = self.func(*self.args)


def download_one(cc):  # <3>
    image = get_flag(cc)
    show(cc)
    save_flag(image, cc.lower() + '.gif')
    return cc


def download_many(cc_list):
    threads = []
    for cc in cc_list:
        thread = MyThread(download_one, (cc, ), download_one.__name__)
        threads.append(thread)

    for thread in threads:
        # 启动线程
        thread.start()

    for thread in threads:
        # wait for all
        # join()会等到线程结束，或者在给了 timeout 参数的时候，等到超时为止。
        # 使用 join()看上去 会比使用一个等待锁释放的无限循环清楚一些(这种锁也被称为"spinlock")
        thread.join()

    return len(list(threads))  # <7>


if __name__ == '__main__':
    main(download_many)