## PART 0 - SCRIPT INFORMATION SECTION ----------------------------------------

#' The script can be used to digitse coordinates from time lapse imagery.
#' 
#' It plots all pictures to be investigated after each other, the displayed 
#' sectin can be cropped to focus on the relevant areas of the picture. By 
#' default the script expects three subsequent clicks per picture: two 
#' calibration or reference scale clicks and one click on the coordinate of 
#' interest. Along with the picture ther will be control buttons plotted. 
#' The OK button is needed to show the next picture after the three clicks 
#' have been set. The Fair button will result in the same but the quality 
#' level in the output data set is reduced to 2 (instead of 1 for the OK 
#' option). The button REPEAT means, well, repeating the clicks on the same 
#' picture. And QUIT means quit. Note however, that R still expects you to 
#' hit the ESC button (the real one from the kayboard) once more to stop the 
#' function locator (used to get mouse click coordinates).
#' 
#' The package makes use of the R implementation of ImageMagick. Thus, make 
#' sure that both imagemagick and the R package magick are installed. Following 
#' the syntax of ImageMagick the crop area is defined by an origin (in this 
#' case the upper left margin of the area of interest) and an extent in x and 
#' y direction. The origin is set with crop_xy_0 and the extent with crop_xy.
#' All units are in pixels. To omit cropping set crop_xy_0 to (0, 0) and 
#' crop_xy to the picture dimensions. You could also think of digitising not 
#' every picture but only those within a time period of interest. For this, 
#' set the variable t_interest as it suits you.
#' 
#' Author: Michael Dietze, Section 5.1 GFZ Potsdam (mdietze@gfz-potsdam.de)
#' 
#' Script version: 0.1.0, 27 August 2018
#' 
#' Changes to previous versions
#'   - not applicable
#' 
#' Requirements & dependencies: 
#'   - R 3.4.4
#'   - magick 1.9

## PART 1 - SETTINGS SECTION --------------------------------------------------

## load package
library("magick")

## set working directory
try(setwd(dir = paste0("~/Documents/projects/Environmental_seismology/",
                       "2017_Ice_covered_rivers/data/images/CAM_2/")))

## define crop area
crop_xy_0 <- c(2530, 1300)
crop_xy <- c(200, 800)

## get files to work on
pictures <- list.files(pattern = "JPG",
                       recursive = TRUE, 
                       full.names = TRUE)

# get picture creation time
t_pictures <- as.POSIXct(x = file.info(pictures)$mtime)

## set time period of interest
t_interest <- as.POSIXct(x = c("2018-05-10",
                               "2018-05-11"),
                         tz = "UTC")

## reduce to time period of interest
pictures <- pictures[t_pictures > t_interest[1] & 
                       t_pictures < t_interest[2]]

## get number of pictures to process
n <- length(pictures)

## create output data set
X <- data.frame(ID = 1:n,
                date = t_pictures[t_pictures > t_interest[1] & 
                                    t_pictures < t_interest[2]],
                file = pictures,
                quality = rep(NA, n),
                x_1 = rep(NA, n),
                y_1 = rep(NA, n),
                x_2 = rep(NA, n),
                y_2 = rep(NA, n),
                x_3 = rep(NA, n),
                y_3 = rep(NA, n),
                t_done = rep(Sys.time(), n))

## PART 2 - EVALUATION SECTION ------------------------------------------------

## print number of working loops
print(paste(n, "files to work on."))

## start processing loop
for(k in 1:n) {
  
  ## read picture
  p <- image_read(pictures[k])
  
  ## crop picture
  p_crop <- image_crop(p, paste0(crop_xy[1], "x", crop_xy[2], "+", 
                                 crop_xy_0[1], "+", crop_xy_0[2]))
  
  ## get control button placement range
  x_range <- c(crop_xy[1] * 4 / 5, 
               crop_xy[1])
  
  y_range <- c(0, crop_xy[2])
  
  ## set control button limits
  x_button <- seq(from = x_range[1], 
                  to = x_range[2], 
                  length.out = 2)
  
  y_button <- seq(from = y_range[1], 
                  to = y_range[2],
                  length.out = 6)
  
  ## define control button labels
  labs <- c("Quit", "", "Ign.", "Fair", "OK")
  
  ## define control button colours
  cols <- c("darkred", "grey40", "red", "orange", "darkgreen")
  
  ## plot cropped picture
  plot(p_crop)
  
  ## add picture ID at bottom of picture
  text(x = 0, 
       y = 5, 
       labels = pictures[k], 
       adj = c(0, 0), 
       col = "white", 
       cex = 0.7)
  
  ## add picture time above ID  
  text(x = 0, 
       y = 25, 
       labels = t_pictures[k], 
       adj = c(0, 0), 
       col = "white", 
       cex = 0.7)
  
  ## add control buttons  
  for(i in 1:5) {
    
    ## add polygons
    polygon(x = c(x_button[1], 
                  x_button[1], 
                  x_button[2], 
                  x_button[2]),
            y = c(y_button[i],
                  y_button[i + 1], 
                  y_button[i + 1], 
                  y_button[i]),
            col = cols[i])
    
    ## add labels
    text(x = mean(c(x_button[1], 
                    x_button[2])), 
         y = mean(c(y_button[i],
                    y_button[i+1])),
         labels = labs[i],
         col = "white",
         adj = c(0.5, 0.5))  
  }
  
  ## define temporary output matrix
  xy_n <- matrix(ncol = 2, 
                 nrow = 3)
  
  ## get up to four mouse click locations
  for(i in 1:4) {
    
    ## get mouse click coordinates
    coord <- locator(n = 1, 
                     type = "n")
    
    ## set dummy quality level
    quality <- NA
    
    ## check Quit case
    if(coord$x >= x_button[1] &
       coord$x <= x_button[2] & 
       coord$y >= y_button[1] & 
       coord$y <= y_button[2]) {
      
      print("Quit")
      k <- n
      break
    }
    
    ## check Ignore case
    if(i <= 4 & 
       coord$x >= x_button[1] &
       coord$x <= x_button[2] & 
       coord$y >= y_button[3] & 
       coord$y <= y_button[4]) {
      
      print("Ignore")
      xy_n <- xy_n * NA
      break
    }
    
    ## save coordinates
    if(i < 4) {
      
      xy_n[i,] <- c(coord$x, 
                    coord$y) 
    }
    
    ## save quality level upon next picture initiation
    if(i == 4 & 
       coord$x >= x_button[1] & 
       coord$x <= x_button[2]) {
      
      if(coord$y >= y_button[4] & 
         coord$y <= y_button[5]) {
        
        quality <- 2
      }
      
      if(coord$y >= y_button[5] & 
         coord$y <= y_button[6]) {
        
        quality <- 1
      }
    }
    
    ## append click number to counter
    cat(i)
  }  
  
  ## print picture just finished in this loop
  print(k)
  
  ## assign results to output data frame
  X$date[k] <- t_pictures[k]
  X$file[k] <- pictures[k]
  X$quality[k] <- quality
  X$x_1[k] <- xy_n[1,1]
  X$y_1[k] <- xy_n[1,2]
  X$x_2[k] <- xy_n[2,1]
  X$y_2[k] <- xy_n[2,2]
  X$x_3[k] <- xy_n[3,1]
  X$y_3[k] <- xy_n[3,2]
  X$t_done <- Sys.time()
}