from base64 import b64encode
from cStringIO import StringIO

import requests
from PIL import Image, ImageSequence, ImageDraw, ImageFont

from ..base import CommandBridle
from ...utils.images2gif import GifWriter


class FlashyGif(object):

    base_image = "https://dl.dropboxusercontent.com/u/176857/flash.gif"
    font_size = 50

    def __init__(self):
        response = requests.get(self.base_image)
        self.base = Image.open(StringIO(response.content))
        self.duration = self.base.info['duration'] / 1000.0
        self.font = ImageFont.truetype(
            'assets/fonts/impact.ttf',
            self.font_size
        )
        self.split_frames()

        self.default_palette = []
        for i in range(256):
            self.default_palette.extend((i, i, i))

    def resize(self, width, height):
        self.width = width
        self.height = height
        frames = []
        for im in self.frames:
            frames.append(im.resize((int(width), int(height))))

        self.frames = frames

    def split_frames(self):
        frames = []
        for frame in ImageSequence.Iterator(self.base):
            frames.append(frame.copy())
        gf = GifWriter()
        self.frames = gf.convertImagesToPIL(frames, False, 0)

    def resize_for_text(self, text):
        draw = ImageDraw.Draw(self.frames[0])
        self.text_width, self.text_height = draw.textsize(text, font=self.font)
        self.resize(self.text_width * 1.04, self.text_height * 1.1)

    def write(self, text):

        self.resize_for_text(text)

        self.durations = []
        self.xys = []
        self.disposes = []

        frames = []
        for im in self.frames:

            palette = self.default_palette[:]
            palette[0] = im.getpalette()[0]
            palette[1] = im.getpalette()[1]
            palette[2] = im.getpalette()[2]
            im.putpalette(palette)

            self.durations.append(self.duration)
            self.xys.append((0, 0))
            self.disposes.append(2)

            draw = ImageDraw.Draw(im)

            draw.text(
                (
                    self.text_width * 0.02,
                    -self.text_height * 0.05
                ),
                text,
                fill=255,
                font=self.font
            )
            frames.append(im)

        self.frames = frames

    def save(self):
        fp = StringIO()
        gf = GifWriter()
        gf.writeGifToFile(
            fp,
            self.frames,
            self.durations,
            0,
            self.xys,
            self.disposes
        )

        fp.seek(0)
        image = b64encode(fp.read())
        payload = {
            'album_id': None,
            'image': image,
            'title': "Autogenerated Flashy Text",
            'description': None
        }

        resp = requests.post(
            "https://api.imgur.com/3/image",
            data=payload,
            headers={
                "Authorization": "Client-ID c3bb952a0a07527"
            }
        )
        return resp.json()['data']['link']


class FlashyText(CommandBridle):

    class Meta(CommandBridle.Meta):
        command = 'flashy'
        description = 'Create a flashy message gif!'
        help_text = ['Usage: `/horse flashy <caption>`']

    def execute(self, user, channel, operands):
        if len(operands) == 0:
            return 'Can\'t flash with nothing, mate'

        flash = FlashyGif()
        flash.write(" ".join(operands).upper())
        image_url = flash.save()

        self.message(
            channel,
            image_url,
            username=user.real_name if user.real_name else user.name,
            icon_url=user.image
        )
