/*
 * Copyright 2012 ios-driver committers.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package org.uiautomation.ios.server.command.uiautomation;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.Response;
import org.uiautomation.ios.communication.WebDriverLikeRequest;
import org.uiautomation.ios.server.IOSServerManager;
import org.uiautomation.ios.server.command.PostHandleDecorator;
import org.uiautomation.ios.server.command.UIAScriptHandler;
import org.uiautomation.ios.utils.FileTo64EncodedStringUtils;

import java.io.File;

public class TakeScreenshotNHandler extends UIAScriptHandler {

  public static final String SCREEN_NAME = "tmpScreenshot";
  private static final
  String
      jsTemplate =
      "UIATarget.localTarget().captureScreenWithName('" + SCREEN_NAME + "');"
      + "UIAutomation.createJSONResponse(':sessionId',0,'ok');";

  public TakeScreenshotNHandler(IOSServerManager driver, WebDriverLikeRequest request) {
    super(driver, request);
    setJS(jsTemplate.replace(":sessionId", request.getSession()));
    addDecorator(new SendBack64EncodedStringDecorator(driver));
  }

  class SendBack64EncodedStringDecorator extends PostHandleDecorator {

    public SendBack64EncodedStringDecorator(IOSServerManager driver) {
      super(driver);
    }

    @Override
    public void decorate(Response response) {

      String
          path =
          getDriver().getSession(getRequest().getSession()).getOutputFolder() + "/Run 1/"
          + SCREEN_NAME
          + ".png";
      File source = new File(path);
      FileTo64EncodedStringUtils encoder = new FileTo64EncodedStringUtils(source);
      try {
        String content64 = encoder.encode();
        source.delete();
        // JSONObject value = new JSONObject();
        // value.put("64encoded", content64);
        response.setValue(content64);
      } catch (Exception e) {
        throw new WebDriverException(
            "Error converting " + source.getAbsolutePath() + " to a 64 encoded string "
            + e.getMessage(), e);
      } finally {
        source.delete();
      }

    }
  }

  @Override
  public JSONObject configurationDescription() throws JSONException {
    return noConfigDefined();
  }
}

@@ -802,16 +802,67 @@
 sponse;%0A
+import org.uiautomation.ios.UIAModels.Orientation;%0A
 import o
@@ -1173,16 +1173,163 @@
 java
-.io.File
+x.imageio.ImageIO;%0Aimport java.awt.*;%0Aimport java.awt.image.BufferedImage;%0Aimport java.io.File;%0Aimport java.io.FileOutputStream;%0Aimport java.io.IOException
 ;%0A%0Ap
@@ -2295,16 +2295,1982 @@
 %22.png%22;%0A
+%0A%0A      int rotateDegrees = 0;%0A      Orientation orientation = getDriver().getSession(getRequest().getSession()).getNativeDriver().getNativeOrientation();%0A%0A      switch(orientation)%0A      %7B%0A        case LANDSCAPE:%0A          rotateDegrees = 270;%0A          break;%0A        case UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT:%0A          rotateDegrees = 90;%0A          break;%0A        case UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN:%0A          rotateDegrees = 180;%0A          break;%0A      %7D%0A%0A      if (rotateDegrees != 0) %7B%0A        try %7B%0A          final BufferedImage originalImage = ImageIO.read(new File(path));%0A%0A          final BufferedImage rotated;%0A          if (rotateDegrees == 90 %7C%7C rotateDegrees == 270) %7B%0A            rotated = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), originalImage.getType());%0A          %7D else %7B%0A            rotated = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), originalImage.getType());%0A          %7D%0A%0A          // Rotate the image and then move it back up to the origin through a translation call, since it'll pivot around%0A          // the center point which will cause non-square images to offset by the different in height and width.%0A          final Graphics2D graphics = rotated.createGraphics();%0A          graphics.rotate(Math.toRadians(rotateDegrees), rotated.getWidth() / 2, rotated.getHeight() / 2);%0A          graphics.translate((rotated.getWidth() - originalImage.getWidth()) / 2, (rotated.getHeight() - originalImage.getHeight()) / 2);%0A          graphics.drawImage(originalImage, 0, 0, originalImage.getWidth(), originalImage.getHeight(), null);%0A%0A          // Overwrite the original screenshot file so the rest of the screenshot handler functions as if the image were never rotated.%0A          final FileOutputStream out = new FileOutputStream(path);%0A          ImageIO.write(rotated, %22PNG%22, out);%0A        %7D catch (IOException e) %7B%0A          throw new RuntimeException(e);%0A        %7D%0A      %7D%0A%0A
       Fi

Correct the orientation for screenshots as they come back from Instruments as always being in portrait.