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

from __future__ import division

import logging
import os

import pexif
import wand.image
from concurrent import futures

from spreads.plugin import HookPlugin

logger = logging.getLogger('spreadsplug.autorotate')


def rotate_image(path, left, right, inverse=False):
    # Silence Wand logger
    (logging.getLogger("wand")
            .setLevel(logging.ERROR))
    logger.debug("Rotating image {0}".format(path))
    # Read the JPEG comment that contains the orientation of the image
    img = pexif.JpegFile.fromFile(path)
    try:
        if img.exif.primary.Orientation == [8]:
            rotation = left
        elif img.exif.primary.Orientation == [6]:
            rotation = right
        else:
            raise Exception("Invalid value for orientation: {0}"
                            .format(img.exif.primary.Orientation))
    except:
        logger.warn("Cannot determine rotation for image {0}!"
                    .format(path))
        return
    if inverse:
                rotation *= 2
    logger.debug("Orientation for \"{0}\" is {1}"
                 .format(path, orientation))
    with wand.image.Image(filename=path) as img:
        logger.debug("Rotating image \'{0}\' by {1} degrees"
                     .format(path, rotation))
        img.rotate(rotation)
        img.save(filename=path)


class AutoRotatePlugin(HookPlugin):
    @classmethod
    def add_arguments(cls, command, parser):
        if command == 'postprocess':
            parser.add_argument("--rotate-inverse", "-ri",
                                dest="rotate_inverse", action="store_true",
                                help="Rotate by +/- 180° instead of +/- 90°")

    def __init__(self, config):
        self.config = config['postprocess']

    def process(self, path):
        img_dir = os.path.join(path, 'raw')
        logger.info("Rotating images in {0}".format(img_dir))
        #num_jobs = self.config['jobs'].get(int)
        #logger.debug("Using {0} cores".format(num_jobs))
        logger.debug("Spawning the processes...")
        with futures.ProcessPoolExecutor() as executor:
            for img in os.listdir(img_dir):
                executor.submit(
                    rotate_image,
                    os.path.join(img_dir, img),
                    inverse=(self.config['autorotate']['rotate_inverse']
                             .get(bool)),
                    left=self.config['autorotate']['left'].get(int),
                    right=self.config['autorotate']['right'].get(int),
                )

@@ -81,21 +81,8 @@
 os%0A%0A
-import pexif%0A
 impo
@@ -125,16 +125,43 @@
  futures
+%0Afrom pexif import JpegFile
 %0A%0Afrom s
@@ -275,870 +275,18 @@
 th, 
-left, right, inverse=False):%0A    # Silence Wand logger%0A    (logging.getLogger(%22wand%22)%0A            .setLevel(logging.ERROR))%0A    logger.debug(%22Rotating image %7B0%7D%22.format(path))%0A    # Read the JPEG comment that contains the orientation of the image%0A    img = pexif.JpegFile.fromFile(path)%0A    try:%0A        if img.exif.primary.Orientation == %5B8%5D:%0A            rotation = left%0A        elif img.exif.primary.Orientation == %5B6%5D:%0A            rotation = right%0A        else:%0A            raise Exception(%22Invalid value for orientation: %7B0%7D%22%0A                            .format(img.exif.primary.Orientation))%0A    except:%0A        logger.warn(%22Cannot determine rotation for image %7B0%7D!%22%0A                    .format(path))%0A        return%0A    if inverse:%0A                rotation *= 2%0A    logger.debug(%22Orientation for %5C%22%7B0%7D%5C%22 is %7B1%7D%22%0A                 .format(path, orientation))
+rotation):
 %0A   
@@ -1275,16 +1275,135 @@
 ecutor:%0A
+            # Silence Wand logger%0A            (logging.getLogger(%22wand%22)%0A                    .setLevel(logging.ERROR))%0A
         
@@ -1413,16 +1413,20 @@
  for img
+path
  in os.l
@@ -1462,106 +1462,284 @@
     
-executor.submit(%0A                    rotate_image,%0A                    os.path.join(img_dir, img),
+img = JpegFile.fromFile(os.path.join(img_dir, imgpath))%0A                try:%0A                    if img.exif.primary.Orientation == %5B8%5D:%0A                        rotation = self.config%5B'autorotate'%5D%5B'left'%5D.get(int)%0A                    elif img.exif.primary.Orientation == %5B6%5D:
 %0A   
@@ -1759,17 +1759,23 @@
     
-inverse=(
+    rotation = 
 self
@@ -1802,65 +1802,354 @@
 %5D%5B'r
-otate_inverse'%5D%0A                             .get(bool
+ight'%5D.get(int)%0A                    else:%0A                        raise Exception(%22Invalid value for orientation: %7B0%7D%22%0A                                        .format(img.exif.primary.Orientation))%0A                except:%0A                    logger.warn(%22Cannot determine rotation for image %7B0%7D!%22%0A                                .format(imgpath
 ))
-,
 %0A   
@@ -2169,13 +2169,36 @@
     
-left=
+continue%0A                if 
 self
@@ -2224,24 +2224,35 @@
 '%5D%5B'
-left
+rotate_inverse
 '%5D.get(
-int),
+bool):
 %0A   
@@ -2273,57 +2273,297 @@
    r
-ight=self.config%5B'autorotate'%5D%5B'right'%5D.get(int),
+otation *= 2%0A                logger.debug(%22Orientation for %5C%22%7B0%7D%5C%22 is %7B1%7D%22%0A                            .format(imgpath, rotation))%0A                executor.submit(%0A                    rotate_image,%0A                    os.path.join(img_dir, imgpath),%0A                    rotation = rotation
 %0A   

Fix multiprocessing code