#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import requests

from django.conf import settings


class DownloadFunc(object):
    base_path = settings.DOWNLOAD_IMAGE_PATH

    @staticmethod
    def get_file_base_path(sole_id=None):

        dir_path = os.path.join(DownloadFunc.base_path, sole_id)

        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        return dir_path

    @staticmethod
    def format_file_abs_path_and_name(dir_path, file_name):
        """
        拼接文件绝对地址
        :param dir_path: 地址
        :param file_name: 文件名
        :return:
        """
        return os.path.join(dir_path, file_name)

    @staticmethod
    def get_url_content(url):
        """
        :param url:
        :return:
        """
        content = b''
        for _ in range(3):
            try:
                response = requests.get(url, timeout=10)
                return response.content
            except:
                raise Exception('download failed')

        return content

    @classmethod
    def download_resources(cls, url, sole_id, suffix=""):
        """
        下载文件资源
        :param url: 下载地址
        :param sole_id:  唯一id
        :param suffix:  后缀
        :return:
        """
        _content = cls.get_url_content(url)
        if _content:
            dir_path = cls.get_file_base_path(sole_id)
            name = url.rsplit("/", 1)[-1]
            if suffix:
                name = "{name}.{suffix}".format(name=name, suffix=suffix)
            file_path = cls.format_file_abs_path_and_name(dir_path, name)
            # 写入本地
            with open(file_path, "wb") as w_:
                w_.write(_content)

            return file_path

        raise Exception("write Failed")


download_img_func = DownloadFunc.download_resources
get_dir_path = DownloadFunc.get_file_base_path
