#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/1/11

import os
from gm_upload import upload
from django.conf import settings
from django.core.management import BaseCommand


UPLOAD_TYPE = 5
TEMP_IMAGE = list()
SEND_TO_REDIS_DICT = dict()
IMAGE_DIRS = os.path.join(settings.BASE_DIR, "new_spring_poster_image")


def search_image(path):
    """
    找到image所在目录, 并且返回该目录下所有的图片
    :param path:
    :return:
    """
    for filename in os.listdir(path):
        if filename.endswith("jpg") or filename.endswith("png"):
            yield filename, filename.split('.')[0].split('_')[-1]


def read_imagedata(filepath):
    """
    读取图片，返回二进制流
    :param path:
    :param mode:
    :return:
    """
    if not filepath:
        return

    full_path = os.path.join(IMAGE_DIRS, filepath)

    if not os.path.exists(full_path):
        return
    with open(full_path, "rb+") as f:
        return f.read()


def sendto_qiniu(data):
    """
    将图片二进制流发送到七牛，获取图片地址
    :param data:
    :return:
    """
    if not data:
        return

    return upload(data, img_type=UPLOAD_TYPE)


def traverse_dirs(path):
    for image, image_type in search_image(path):
        TEMP_IMAGE.append([sendto_qiniu(read_imagedata(image)), image_type])


class Command(BaseCommand):
    def handle(self, *args, **options):
        print('--------start traverse dirs----------------')
        traverse_dirs(IMAGE_DIRS)
        print('--------end traverse dirs----------------')