"""
-------------------------------------------------------------------------
   File Name：     downloader
   Description :
   Author :        JHao
   date:          2022/7/28
   last:          2022/8/12
-------------------------------------------------------------------------
   Change Activity:
                   2022/8/12:
                             1.添加头部说明信息、作者
                             2.增加参数（有默认值）
                                请求头headers
                                分块大小length
                             3.更改进度条样式，支持显示下载速度
                                update1：解决计算速度漏记读取时间
                                update2：解决块不足、文件过小时速度值超高问题
                             4.更改返回值模式
                             5.添加判断请求返回状态码
                             6.添加处理响应头不包含文件大小的情况
                             7.添加显示参数类型
                             8.添加部分说明注释，解决bug
-------------------------------------------------------------------------
"""
__author__ = 'Jerry Best'

import time
import requests
import os


class Downloader:
    def __init__(self, headers: str = '', length: int = 0):
        """
        参数配置
        :param headers: 请求头(如有特殊要求)
        :param length: 分段下载长度
        """
        if not length:
            self._WINDOWS = os.name == 'nt'
            self.COPY_BUF_SIZE = 1024 * 1024 if self._WINDOWS else 64 * 1024
        if headers == '':
            self.headers = {'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):
        """
        文件大小转易读格式
        :param size:
        :return:
        """
        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 "%.2f 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: 分块大小
        """
        # 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% [', ' ' * 40, ']', sep='', end='')
        # console_width = os.get_terminal_size().columns - 20
        while True:
            time_start = time.perf_counter()
            buf = fsrc_read(length)
            if not buf:
                break
            fdst_write(buf)
            time_end = time.perf_counter()
            length_read = len(buf)
            try:
                speed = length_read / (time_end - time_start)
            except ZeroDivisionError:
                speed = 0
            i += length_read
            sp = i / size
            if sp > 1:
                sp = 1
            print(f'\r', format(sp * 100, '.2f'), '% [',
                  '▉' * int(40 * sp), ' ' * (40 - int(40 * sp)), ']  ',
                  self._format_size(speed), '/s',
                  sep='', end='')
        print('\n')

    def download_file(self, url: str, path: str, redown: int = 0):
        """
        文件下载
        :param url: 下载文件url
        :param path: 保存路径 需要文件名和扩展名
        :param redown: 是否询问重新下载(0:询问 1:默认不重新下载 2:默认重新下载)
        :return:
            成功:0
            失败:  1: (未知错误)
                  url: (请求状态码错误)
        """
        print(url.split('/')[-1], '=>', path.split('/')[-1], end='  ')
        if os.path.exists(path):
            if redown == 0:
                if input('\n文件已存在,是否重新下载? (y/n)') != 'y':
                    print('')
                    return 0
            elif redown == 1:
                print('')
                return 0
            # print('\b\b \r')
            os.remove(path)

        with requests.get(url, stream=True, headers=self.headers) as r:
            if r.status_code != 200:
                print('Fail', r.status_code)
                return url

            with open(path + '.tmp', 'wb') as f:
                try:
                    size = int(r.headers['Content-Length'])
                except KeyError:
                    size = 1
                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()
    _time_start = time.time()
    'https://mirrors.tuna.tsinghua.edu.cn/debian-cd/11.4.0/amd64/iso-cd/debian-edu-11.4.0-amd64-netinst.iso''440MB'
    'https://mirrors.tuna.tsinghua.edu.cn/deepin-cd/20.6/deepin-desktop-community-20.6'
    '-amd64.iso''3.22g'
    'https://blog.jerrybest.tk/wp-content/uploads/2022/06/szg_7991_50001_0b53riaagaaal4'
    'akz3ko7jrfdcwdaofaaa2a.f632.mp4'
    print(d.download_file('https://blog.jerrybest.tk/wp-content/uploads/2022/06/szg_7991_50001_0b53riaagaaal4'
                          'akz3ko7jrfdcwdaofaaa2a.f632.mp4', './test.iso'))

    _time_end = time.time()
    print(_time_end - _time_start)
    # md5 = MD5()
    # print(md5.local('./test.iso'))
