from datetime import datetime
import os
import io
import tempfile
import requests
from PIL import Image


class Generator(object):

    def __init__(self, generator=None, folder=None):
        self.selected_folder = folder
        if generator == 'poses':
            self.generate_poses()

    def generate_poses(self):
        dt = datetime.now()
        ts = int(datetime.timestamp(dt))
        url = 'https://quickposes.com/ajax/getPosesForSlider/Chiaroscuro?_=' + str(ts)

        resp_json = requests.get(url=url)
        if resp_json.status_code == 200:
            data = resp_json.json()
            c = 0
            for src in data:
                if os.path.exists(os.path.join(self.selected_folder, src['src'])):
                    continue
                if c >= 3:
                    break
                buffer = tempfile.SpooledTemporaryFile(max_size=1e9)
                r = requests.get('https://quickposes.com/assets/poses/' + src['src'], stream=True)
                if r.status_code == 200:
                    downloaded = 0
                    for chunk in r.iter_content(chunk_size=1024):
                        downloaded += len(chunk)
                        buffer.write(chunk)
                    buffer.seek(0)
                    i = Image.open(io.BytesIO(buffer.read()))
                    i.save(os.path.join(self.selected_folder, src['src']), quality=85)
                buffer.close()
                c += 1
