package org.crepi22.finecrop;

import java.io.File;
import java.util.Arrays;

class Rotate extends Thread {
    final double angle;
    final Continuation continuation;
    final Photo photo;

    Rotate(Continuation continuation, Photo photo, int startX, int startY, int endX, int endY) {
        this.photo = photo;
        int dx = endX - startX;
        int dy = endY - startY;
        if (dx == 0) angle = 0;
        else angle = Math.atan((float) dy / dx) / Math.PI * 180;
        this.continuation = continuation;
    }

    Rotate(Continuation continuation, Photo photo,  double angle) {
        this.photo = photo;
        this.continuation = continuation;
        this.angle = angle; 
    }
    
    @Override
    public void run() {
        
        synchronized (continuation) {
            try {
                continuation.showEffect(true);
                File rotatedImageFile = File.createTempFile("rotated", ".jpg");;     //$NON-NLS-1$ //$NON-NLS-2$
                String[] command = new String[] {
                        Config.getConvertPath(),
                        "-rotate", //$NON-NLS-1$
                        String.format("%.2f", -angle), //$NON-NLS-1$
                        photo.getPath(),
                        rotatedImageFile.getAbsolutePath()
                };
                
                Process p = Runtime.getRuntime().exec(command);
                int exit = p.waitFor();
                if (exit == 0) {
                    continuation.runFile(rotatedImageFile);
                } else {
                    continuation.error(String.format(Messages.getString("Rotate.command_error"),exit, Arrays.toString(command))); //$NON-NLS-1$
                }
            } catch (Exception e) {
                continuation.error(e.getMessage());
            } finally {
                continuation.showEffect(false);
                
            }
        }

    }
}