import codecs
from contextlib import contextmanager
from cStringIO import StringIO
import json
import os
import shutil
import socket
import tempfile
import urllib2

from django.conf import settings
from django.core import mail
from django.core.files.storage import default_storage as storage

import mock
from nose.tools import eq_
from PIL import Image

import amo
import amo.tests
from addons.models import Preview
from amo.tests.test_helpers import get_image_path
from amo.urlresolvers import reverse
from amo.utils import ImageCheck
from files.models import FileUpload

import mkt
from mkt.developers import tasks
from mkt.site.fixtures import fixture
from mkt.submit.tests.test_views import BaseWebAppTest
from mkt.webapps.models import AddonExcludedRegion as AER, Webapp


def test_resize_icon_shrink():
    """ Image should be shrunk so that the longest side is 32px. """

    resize_size = 32
    final_size = (32, 12)

    _uploader(resize_size, final_size)


def test_resize_icon_enlarge():
    """ Image stays the same, since the new size is bigger than both sides. """

    resize_size = 1000
    final_size = (339, 128)

    _uploader(resize_size, final_size)


def test_resize_icon_same():
    """ Image stays the same, since the new size is the same. """

    resize_size = 339
    final_size = (339, 128)

    _uploader(resize_size, final_size)


def test_resize_icon_list():
    """ Resize multiple images at once. """

    resize_size = [32, 82, 100]
    final_size = [(32, 12), (82, 30), (100, 37)]

    _uploader(resize_size, final_size)


def _uploader(resize_size, final_size):
    img = get_image_path('mozilla.png')
    original_size = (339, 128)

    src = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                      delete=False)

    # resize_icon removes the original
    shutil.copyfile(img, src.name)

    with storage.open(src.name) as fp:
        src_image = Image.open(fp)
        src_image.load()
    eq_(src_image.size, original_size)

    if isinstance(final_size, list):
        for rsize, fsize in zip(resize_size, final_size):
            dest_name = os.path.join(settings.ADDON_ICONS_PATH, '1234')

            tasks.resize_icon(src.name, dest_name, resize_size, locally=True)
            with storage.open("%s-%s.png" % (dest_name, rsize)) as fp: