import logging
import json
import shutil
from io import BytesIO

import requests

from django.core.files import File
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile

from faker import Faker
from PIL import Image

from companies.factories import CompanyFactory
from companies.models import Company
from products.factories import ProductFactory
from products.models import Product


logging.basicConfig(
    filename='logs/addtestdata.log',
    filemode='w',
    format='%(levelname)s:%(message)s',
    level=logging.INFO,
    )


class Command(BaseCommand):

    logo_url = "https://picsum.photos/300/200"
    help = 'Creates fake companies and related products in database'

    def handle(self, *args, **kwargs):
        print("Create fake data to populate database\n")
        '''
        print("Deleting existing Product and Company instances")
        Product.objects.all().delete()
        Company.objects.all().delete()
        '''
        # start faker
        fake = Faker()
        Faker.seed(0)

        # companies created
        new_companies = []
        logging.info("Creating fake companies")
        print("Creating fake companies")
        for i in range(10):
            name = f"{fake.company()} {fake.company_suffix()}"
            company = CompanyFactory(company_name=name)
            new_companies.append(company)
            logging.debug(f"New Company {company.company_name} created")
            print(f"\t- {name}")
        print('')

        logging.info("Creating fake products")

        # create and assign products to companies
        for company in new_companies:
            print(f"Creating fake products for {company.company_name}")
            logging.info(f"Creating fake Products for {company.company_name}")
            # for i in range(100):
            for i in range(10):
                # make up data
                name = fake.last_name_nonbinary()
                description = fake.paragraph(nb_sentences=5)
                # TODO: apply automatic tags from tag list
                # TODO: write image to S3 storage
                # create instance
                product = ProductFactory(
                    company=company,
                    name=name,
                    description=description)

                # get image
                response = requests.get(self.logo_url, stream=True)
                response.raw.decode_content = True
                image = Image.open(response.raw)

                # save using File object
                img_io = BytesIO()
                image.save(img_io, format='JPEG')
                product.image.save(f"{company.company_name}-{name}.jpg", File(img_io), save=False)
                product.save()

                logging.debug(f"New Product {product.name} created")
            print('')

        print("Dataset creation finished")