import requests
import os


class Downloader:
    def __init__(self):
        self._WINDOWS = os.name == 'nt'
        self.COPY_BUF_SIZE = 1024 * 1024 if self._WINDOWS else 64 * 1024
        self.header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                                     'like Gecko) Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.71'}

    @staticmethod
    def _format_size(size):
        kb = float(size) / 1024

        if kb >= 1024:
            m = kb / 1024
            if m >= 1024:
                g = m / 1024
                return "%.2f G" % g
            else:
                return "%.2f M" % m
        elif 1 <= kb:
            return "%.2f K" % kb
        else:
            return "%f B" % size

    def _copyfileobj(self, fsrc, fdst, size, length=0):
        """
        copy data from file-like object fsrc to file-like object fdst
        :param fsrc: 被拷贝文件
        :param fdst: 目标文件
        :param size: 文件大小(B)
        :param length: 分块大小
        :return:
        """
        # Localize variable access to minimize overhead.
        if not length:
            length = self.COPY_BUF_SIZE
        fsrc_read = fsrc.read
        fdst_write = fdst.write
        i = 0
        print('0.00% |', end='')
        while True:
            buf = fsrc_read(length)
            if not buf:
                break
            fdst_write(buf)
            i += length
            sp = i / size
            if sp > 1:
                sp = 1
            print(f'\r', format(sp * 100, '.2f'), '% |', '▊' * int(40 * sp), sep='', end='')
        print('\n')

    def download_file(self, url, path, redown=0):
        """文件下载
        :param url: 下载文件url
        :param path: 保存路径 需要文件名和扩展名
        :param redown: 是否询问重新下载(0:询问 1:默认不重新下载 2:默认重新下载)
        :return: 成功:0 失败:1
        """
        print(url.split('/')[-1], '=>', path.split('/')[-1], end='  ')
        if os.path.exists(path):
            if redown == 0:
                if input('\n文件已存在,是否重新下载? (y/n)') != 'y':
                    print('\n')
                    return 0
            elif redown == 1:
                print('\n')
                return 0
            os.remove(path)

        with requests.get(url, stream=True, headers=self.header) as r:
            with open(path + '.tmp', 'wb') as f:
                size = int(r.headers['Content-Length'])
                print('total: ', self._format_size(size), sep='')
                self._copyfileobj(r.raw, f, size)
        try:
            os.rename(path + '.tmp', path)
        except FileExistsError:
            print('\n')
            return 1
        return 0


if __name__ == '__main__':
    d = Downloader()
    # 'https://mirrors.tuna.tsinghua.edu.cn/debian-cd/11.4.0/amd64/iso-cd/debian-edu-11.4.0-amd64-netinst.iso''440MB'
    print(d.download_file('https://mirrors.tuna.tsinghua.edu.cn/deepin-cd/20.6/deepin-desktop-community-20.6'
                          '-amd64.iso', './test.iso'))
    # md5 = MD5()
    # print(md5.local('./test.iso'))
