
### whichmedian function returns middle point among N points
whichmedian <- function(x) which.min(abs(x - median(x)))
################################################################################
## st_Donut_all function generates polygon-based obfuscated area and obfuscated polygon for each field parcels 
## using PRand method (type = 1), PDonut method (type = 2) or PDensity method (type = 3)
## area is non sensitive area which is study area without field parcels (area = orgmock_nonsen )
## input_data and mdata are updated file from previous step 
## k: desired k-anonymity (here fortype = 1 k = 5 but for type= 2 and type 3 k = k2 -k1 = 12-5 = 7),
## nr: start from this row (should be start from 1 but for checking the program can be started from any row) 
## t: number of rows, 
## mapflag: TRUE(generate map)/False (not generate map) 
## N: number of random points in type =1 N = 5
## for type = 2 and type = 3 N = 1
st_Dounat_all <- function(area,input_data,mdata,N,R1,R2,type,mapflag,nr,t,k){
  start_time <- Sys.time()
  pnt <- input_data
  np <- nrow(pnt)
  obf_p <- data.frame(plotUID = integer(np),
                      obf_x = double(np),
                      obf_y = double(np),
                      oave_x = double(np),
                      oave_y = double(np))
  coordinates(obf_p) <- ~ obf_x +obf_y
  coordinates(pnt) <- ~ cnt_x + cnt_y
  crs(pnt) <- CRS("+init=epsg:2157")
  pnt <- st_as_sf(pnt)
  ############################
  obf_p <- st_as_sf(obf_p)
  st_crs(obf_p) <- st_crs(pnt)

  #type = 1 N*rand method
  if (type == 1 & N == 1){
    mdata$orand_x <- 0
    mdata$orand_y <- 0
  }
  ##  type = 1 two methods (PNRand and PNMix) create obfuscated coordinates
  if (type == 1 & N > 1){
    mdata$omax_x5 <- 0   
    mdata$omax_y5 <- 0
    mdata$oave_x5 <- 0
    mdata$oave_y5 <- 0
  }
  #Type = 2 donut method create obfuscated coordinates 
  if (type == 2 &  N == 1){
    mdata$dt_orand_x <- 0
    mdata$dt_orand_y <- 0
  }
  if (type == 2 & N > 1){
    mdata$dt_omax_x <- 0
    mdata$dt_omax_y <- 0
    mdata$dt_oave_x <- 0
    mdata$dt_oave_y <- 0
  }
  #Type = 3 density methodcreate obfuscated coordinates  
  if (type == 3 & N > 1){
    mdata$denomaxk6_x5 <- 0
    mdata$denomaxk6_y5 <- 0
    mdata$denoavek6_x5 <- 0
    mdata$denoavek6_y5 <- 0
  }
  ### type 3 for density method create obfuscated coordinates
  if (type == 3 &  N == 1){
    mdata$denorandk11k_x <- 0
    mdata$denorandk11k_y <- 0
  }
  ushape_all <<- area
  nrt <- nr + t -1
  for (center_p in nr:nrt){
    print(center_p)
    center_lonlat <- pnt$geometry[center_p]
    if (type == 1){
      # instead of ushape_all area bodeh
      mm <- c(R1, R2)
      ##  returns obfuscated coordinates ( 1 or 2 depends on value of N)
      obf_p <- st_pl_allpnt_rand(ushape_all,mm,pnt,N,center_lonlat,center_p,mapflag,obf_p,k,mdata)
      ##  update the mdata and add the obfuscated coordinates to output file 
      if (N == 1){
        mdata$orand_x[center_p] <- obf_p$geometry[[center_p]][1]
        mdata$orand_y[center_p] <- obf_p$geometry[[center_p]][2]
      }
      else{
        mdata$oave_x5[center_p] <- obf_p$oave_x[center_p]
        mdata$oave_y5[center_p] <- obf_p$oave_y[center_p]
        mdata$omax_x5[center_p] <- obf_p$geometry[[center_p]][1]
        mdata$omax_y5[center_p] <- obf_p$geometry[[center_p]][2]
      }
    }
    else{
      if (type == 2){
        mm <- c(max(mdata$maxk_R1), max(mdata$maxk11_R2))
      }
      if (type == 3)
        mm <- c(mdata$maxk_R1[center_p],mdata$maxk11_R2[center_p])
      obf_p <- st_pl_allpnt_rand(ushape_all,mm,pnt,N,center_lonlat,center_p,mapflag,obf_p,k,mdata)
      if (type == 2 &  N == 1){
        mdata$dt_orand_x[center_p] <- obf_p$geometry[[center_p]][1]
        mdata$dt_orand_y[center_p] <- obf_p$geometry[[center_p]][2]
      }
      if (type == 2 & N > 1){
        mdata$dt_oave_x[center_p] <- obf_p$oave_x[center_p]
        mdata$dt_oave_y[center_p] <- obf_p$oave_y[center_p]
        mdata$dt_omax_x[center_p] <- obf_p$geometry[[center_p]][1]
        mdata$dt_omax_y[center_p] <- obf_p$geometry[[center_p]][2]
      }
      
      if (type == 3 &  N == 1){
        mdata$denorandk11k_x[center_p] <- obf_p$geometry[[center_p]][1]
        mdata$denorandk11k_y[center_p] <- obf_p$geometry[[center_p]][2]
      }
      if (type == 3 & N > 1){
        mdata$denoavek6_x5[center_p] <- obf_p$oave_x[center_p]
        mdata$denoavek6_y5[center_p] <- obf_p$oave_y[center_p]
        mdata$denomaxk6_x5[center_p] <- obf_p$geometry[[center_p]][1]
        mdata$denomaxk6_y5[center_p] <- obf_p$geometry[[center_p]][2]
      }
    }
  }
  print(Sys.time() - start_time)
  return(mdata)
}
st_pl_allpnt_rand <- function(shape_all,mm,pnt,N,cnt,center_p,mapflag,obf_p,k,input_data,num_loop){
  continue <- TRUE
  bufk <- st_buffer(pnt$geometry[center_p], input_data$maxd_edge[center_p])
  area_bufk <- st_area(bufk)
  center_buf1 <- st_buffer(pnt$geometry[center_p], mm[1])
  if (mm[2] > mm[1]+2 * input_data$maxd_edge[center_p])
    mm2 <- mm[2]
  else{
    mm2 <- mm[2] + 2* input_data$maxd_edge[center_p]
  }
  ##  obfuscation area generation
  while (continue ) 
  {
    center_buf2 <- st_buffer(pnt$geometry[center_p], mm2)
    buf <-  st_difference(center_buf2,center_buf1)
    if (mapflag)
      plot(buf)
    ## generate obfuscated area 
    buf <- st_intersection(buf,ushape_all)
    ## remove extended sensitive area from obfuscate area
    buf_ushape <- st_buffer(buf,-input_data$maxd_edge[center_p])
    area_u <- st_area(buf_ushape)
    dif_area <- k * area_bufk - area_u
    ## gradually increase the size of obfuscation area that would be at least k times of size of original polygon 
    if (k * area_bufk  > st_area(buf_ushape) )
      mm2 <- mm2 + 2 * input_data$maxd_edge[center_p]
    else
      continue <- FALSE
  }
  ######################################### 
  ### select random point as a obfuscated point inside obfuscated area
  rand_point <- st_sample(buf_ushape , N)
  obf_p$plotUID[center_p] <- center_p
  if (N > 1){
    ix <-  which.max(st_distance(rand_point,cnt))
    obf_p$geometry[center_p] <- rand_point[[ix]]
    ixm <- whichmedian(st_distance(rand_point,cnt))
    obf_p$oave_x[center_p] <- st_coordinates(rand_point)[ixm,1]
    obf_p$oave_y[center_p]  <- st_coordinates(rand_point)[ixm,2]
  }
  else{
    ix <- 1
    obf_p$geometry[center_p] <- rand_point[[ix]]
  }
  ## generate  maximum obfuscated polygon (MOP). 
  tmp_poly <- st_buffer(obf_p$geometry[center_p],input_data$maxd_edge[center_p])
  ## remove MOP from obfuscated area
  ushape_all <<- st_difference(ushape_all,tmp_poly)
  ##  plot Fig1
  if (mapflag){
    plot(buf,add = TRUE,col = transparent( 'pink', trans.val = .7))
    plot(buf_ushape,add = TRUE,col = transparent( 'green', trans.val = .5))
    plot(pnt$geometry[center_p],col='red', add = TRUE, cex = 1,pch = 20)
    plot(tmp_poly,add = TRUE,col = transparent( 'blue', trans.val = .5))
    plot(rand_point[[ix]],add = TRUE, col='red',pch='*',cex=2)
  } 
  return(obf_p)
}

#########################################################################################################
## example to generate Figure1 
Ntest <- st_Dounat_all(orgmock_nonsen,orgmock_k1_5_k2_12_tmp,orgmock_k1_5_k2_12_tmp,5,1,25000,3,TRUE,500,5,5)
##  run the program for 3 types of obfuscation methods for all rows
Ntest <- st_Dounat_all(orgmock_nonsen,orgmock_k1_5_k2_12_tmp,orgmock_k1_5_k2_12,5,1,25000,1,FALSE,1,nrow(orgmock_k1_5_k2_12_tmp),5)
