# -*- coding: utf-8 -*-

import os

from django_six import CompatibilityBaseCommand

from utils.qiniucdn import upload_file_path


class Command(CompatibilityBaseCommand):
    def handle(self, *args, **options):

        dirs = ['media/file']

        for dir in dirs:
            for root, dirs, files in os.walk(dir):
                print('')
                print('Root: {}'.format(root))
                print('Dirs: {}'.format(dirs))
                print('Files: {}'.format(files))
                if not dirs and not files:
                    os.rmdir(root)
                for file in files:
                    print('  >> File: {}'.format(file))
                    ext = file.split('.')[-1]
                    if not ext:
                        continue
                    if ext.lower() not in ['jpg', 'jpeg', 'png', 'heic']:
                        continue
                    try:
                        file_path = '{}/{}'.format(root, file)
                        if os.path.exists(file_path):
                            qiniu_key = 'fujifilm/uncompressed/{}'.format(file_path)
                            print('    >> File Path: {}'.format(file_path))
                            print('    >> Qiniu Path: {}'.format(qiniu_key))
                            upload_file_path(file_path, key=qiniu_key, bucket='tamron', compress=False)
                            os.remove(file_path)
                    except Exception:
                        pass