
if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("HilbertCurve")

library(HilbertCurve)
## Hil <- HilbertCurve(1,100,level =1,reference = TRUE)
## function to generate Hilbert data structure contains Hilbert curve order,
## number of polygon and index of each cell
grid_fun_H <- function(area,lvl,area_p,mapflag){
  start_time <- Sys.time()
  Hil <- HilbertCurve(1,100,level = lvl,reference = FALSE)
  res <- 2 ^lvl
  grid <- raster(area, ncol = res, nrow = res)
  grid_poly <- rasterToPolygons(grid)
  # grid_area <- intersect(grid_poly,area)
  grid_area <- gIntersection(grid_poly,area)
  if (mapflag)
    plot(grid_area)
  x <- rasterize(area_p,grid,fun = 'count')
  df.Hil <- data.frame(Ind = integer(),OId= integer(),Hvalue = integer(),Num = integer())
  for (i in 1:nrow(grid) )
  {
    Hy <- res-i +1
    Oy <- i 
    Ti <- i - 1
    for (j in 1:ncol(grid) )
    {
      ind <- j + (res *(i -1))
      df.Hil[ind,] <- NA
      df.Hil$OId[ind] <- res * (Hy - Oy) + ind
      ii <- df.Hil$OId[ind] 
      Tj <- j - 1
      if (i == 1  & j == res)
        df.Hil$Hvalue[ind] <- res * res
      else 
        df.Hil$Hvalue[ind] <- which(Hil@POS$x1 == Tj & Hil@POS$y1 == Ti)
      df.Hil$Num[ind] <- x@data@values[ii]
      #df.Hil$Num[ind] <- x@data@values[ii,1]
      if (is.na(df.Hil$Num[ind])) 
        df.Hil$Num[ind] <- 0
      df.Hil$Ind[ind] <- ind
      txt <- paste(df.Hil$Hvalue[ind])
      if (mapflag)
        text(x = grid_poly@polygons[[ii]]@labpt[1], y = grid_poly@polygons[[ii]]@labpt[2],col='black',txt,cex = 0.6)
    }
    
  }
  print(Sys.time() - start_time)
  return(c("polyg"= grid_poly,"x" = x,"df"= df.Hil))
}

## prior to run the Hilbert methods we need to generate the Hilbert data structure 
## with resolution 256 (lvl = 8) this is time consuming you can use provided H8t below and
## try to generate above data structure for resolution 16(lvl = 4) to test the code 
## and see the output when mapflage = TRUE
H4t <- grid_fun_H(Corkt,4,orgmock_data[9:10],TRUE)
H4 <- grid_fun_H(Cork,4,orgmock_data[9:10],TRUE)
H8t <- grid_fun_H(Corkt,8,orgmock_data[9:10],FALSE)
##################################################################################

## getcoord function returns row or column number of cell that contains a point p 
## in a girded study area with given resolution res, cell with length l
getcoord <- function(res,l,p,minp){
  tmpx <- 0
  xi <- 1
  flag <- TRUE
  while (flag & xi < res+1){
    tmpx <- minp + (xi * l)
    if (tmpx  < p)
      xi <- xi +1
    else
      flag <- FALSE
  }
  return(xi)
}

## ply_grid generates a polygon of cell with index of ii and sides 'length of lx and ly
## in a Hilbert data structure H
#######################################################################################
######  check compile and checkkkkkk####################
ply_grid <- function(H,lx,ly,ii){
  x_coord <- numeric()
  y_coord <- numeric()
  lx2 <- round(lx/2,2) +0.01
  ly2 <- round(ly/2,2) +0.01
  ## start from the coordinate of lower right corner of a cell
  x_coord <- append(x_coord,H$polyg@polygons[[ii]]@labpt[1]+lx2)
  y_coord <- append(y_coord,H$polyg@polygons[[ii]]@labpt[2] -ly2)
  ## obtain the coordinate ofupper right corner of a cell
  x_coord <- append(x_coord,H$polyg@polygons[[ii]]@labpt[1]+lx2)
  y_coord <- append(y_coord,H$polyg@polygons[[ii]]@labpt[2] +ly2)
  ## obtain the coordinate of upper left corner of a cell
  x_coord <- append(x_coord,H$polyg@polygons[[ii]]@labpt[1]-lx2)
  y_coord <- append(y_coord,H$polyg@polygons[[ii]]@labpt[2] +ly2)
  ## obtain the coordinate of lower left corner of a cell
  x_coord <- append(x_coord,H$polyg@polygons[[ii]]@labpt[1]-lx2)
  y_coord <- append(y_coord,H$polyg@polygons[[ii]]@labpt[2] -ly2)
  ## back to the coordinate of lower right corner of a cell
  x_coord <- append(x_coord,H$polyg@polygons[[ii]]@labpt[1]+lx2)
  y_coord <- append(y_coord,H$polyg@polygons[[ii]]@labpt[2] -ly2)
  ## generate a polygon with above pairs of coordinates
  xy <- cbind(x_coord,y_coord)
  p <- Polygon(xy)
  ps <- Polygons(list(p),0)
  sps <- st_as_sf(SpatialPolygons(list(ps)))
  return(sps)
}

## generate a output mdata with adding obfuscated polygons to a given input_data in a study area
## of area using Hibert data structure have been  generated above with lvl: level of H,k: desired k-anonymity, 
## nr: start from this row (should be start from 1) t: number of rows, mapflag: TRUE(generate map)/False (not generate map) 
plyst_grid_H_all_obfpoly <- function(area,input_data,mdata,lvl,k,nr,t,N,mapflag,H){
  start_time <- Sys.time()
  if (nr != 1){
    print('Please start from one')
    return()
  }
  alpha1 <- 0.25
  pnt <- input_data
  lpnt <- nrow(pnt)
  coordinates(pnt) <- ~ cnt_x + cnt_y
  crs(pnt) <- CRS("+init=epsg:2157")
  res = 2^ lvl
  d <- res *res

  ## define threshold for a total area of obfuscated area to increase processing time and 
  ## avoid to generate obfuscated polygon be too far this can be consider as 1/10 0f area of study area
  ## for Ireland we have considered as 5000000 and for this mock study area 3000000
  trsh_area <- 3000000
  # trsh_area <- 5000000
  pnt <- st_as_sf(pnt)
  area <- st_as_sf(area)
  area <- st_transform(area,crs =  st_crs(pnt))
  ##########################################
  ### define a structure for obfuscated point as a Centroid of a obfuscated polygon
  obf_all <- data.frame(plotUID = integer(lpnt),
                        obf_x = double(lpnt),
                        obf_y = double(lpnt))
  coordinates(obf_all) <- ~ obf_x +obf_y
  crs(obf_all) <- CRS("+init=epsg:2157")
  obf_all <- st_as_sf(obf_all)
  nrt <- nr + t-1
  ##add new variables as a obfuscated coordinates of centroid of obfuscated polygon to output data
  mdata$hoave_x <- 0
  mdata$hoave_y <- 0
  totalp <- 0            ## number of polygons
  total_ply <- c(numpoly = 0,areapoly = area)   ##number of polygons and total area 
  tag1 <- TRUE
  for (center_p in nr:nrt)
  {
    print(center_p)
    visited_cell <- c()          # previous visited cells 
    visited_ngh <<- c()          # previous visited neighbors of a cell
    org_shape <- readWKB( pnt$plot_shape[center_p]) ## polygon 
    org_shape <- SpatialPolygons(list(Polygons(list(org_shape@polygons[[1]]@Polygons[[1]]),ID=1)))
    org_shape <- st_as_sf(org_shape)
    st_crs(org_shape) <- st_crs(pnt)
    ## k times of area of a polygon as a minimum size of obfuscated area
    area_bufk <-drop_units(st_area(org_shape)) * k    
    center_lonlat <- pnt$geometry[center_p]
    ## sides' length of each cell in Hilbert curve H with resurrection res
    lx <- (H$x@extent@xmax - H$x@extent@xmin) / res
    ly <- (H$x@extent@ymax - H$x@extent@ymin) / res
    #row and column number of cell that contains a point p in a girded study area H
    xres <- getcoord(res,lx,mdata$cnt_x[center_p],H$x@extent@xmin)
    yres <- getcoord(res,ly,mdata$cnt_y[center_p],H$x@extent@ymin) -1
    next_ind <- (xres + yres* H$x@ncols)   ## index of cell(xres,yres)
    print(next_ind)
    i <- 1
    totalk <- 0
    num_poly <- 0
    tag <<- FALSE
    tag_obf_all <-TRUE
    tag2 <- FALSE
    totalk <- H$df.Num[next_ind]
    visited_cell[i] <- H$df.OId[next_ind] ## add this cell to visited cells
    #####obf_p[i] <- H$df.OId[next_ind] ## add this cell to visited cells
    ## returns number of complete polygons inside a cell(visited_cell[i]) and its 8 neighbors
    ## and obfuscation area based on this cell and its 8 neighbors
    total_ply <- ply_numpolyg_obfpoly(area,H,pnt,total_ply,tag,visited_cell[i],
                                      lx,ly,visited_cell,visited_ngh,res,obf_all,center_p,mapflag)
    ## add visited neighbors cell to visited cell
    l <- length(visited_ngh)
    i <- i +1
    if(l > 0 ){
      il <- i+l-1
      visited_cell[i:il] <- visited_ngh[1:l]
      i <- i+l
    }
    tag2 <- TRUE
    j <- 0
    ##  consider the cell’s four neighbors left, right, down and up with considering the cell boundaries 
    ## and then cell follow by Hilbert value order 
    while ( ( (drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) < trsh_area) &
              (total_ply$numpoly < k | drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) <= area_bufk) )
            & H$df.OId[next_ind] < d) {
      j <- j + 1
      ##  cell's left neighbor considering the cell bounders
      if ((next_ind -1) %% res != 0)
       if (!H$df.OId[next_ind -1]%in% visited_cell & H$df.Hvalue[next_ind -1] != H$df.Hvalue[next_ind]+1  )
        if (total_ply$numpoly < k | drop_units(st_area(st_buffer(total_ply$areapoly ,
                                           -pnt$maxd_edge[center_p]))) < trsh_area){
          totalk <- totalk +  H$df.Num[next_ind -1]
          visited_cell[i] <- H$df.OId[next_ind-1]
          total_ply <- ply_numpolyg_obfpoly(area,H,pnt,total_ply,tag,visited_cell[i],
                                            lx,ly,visited_cell,visited_ngh,res,obf_all,center_p,mapflag)
          
          lnext <- length(visited_ngh)
          i <- i+1
          if(l != lnext ){
            ln <- lnext-l
            il <- i +lnext-l-1
            visited_cell[i: il] <- visited_ngh[l:ln]
            i <- i+lnext -l
            l <- lnext
          }
        }
      ##  cell's right neighbor considering the cell bounders
      if ((next_ind +1) %% res != 1) 
        if (!H$df.OId[next_ind +1] %in% visited_cell & H$df.Hvalue[next_ind +1] != H$df.Hvalue[next_ind]+1  )
        ###// & H$df.Num[next_ind +1] > 0)
        if ((total_ply$numpoly < k & drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) <= area_bufk) 
            | drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) < trsh_area){
          totalk <- totalk +  H$df.Num[next_ind + 1]
          visited_cell[i] <- H$df.OId[next_ind +1]
          ##  print(paste('iii', i, 'obf_pcenter2222',obf_p[i], 'numof point hilbert',H$df.Num[next_ind +1]))
          total_ply <- ply_numpolyg_obfpoly(area,H,pnt,total_ply,tag,visited_cell[i],
                                            lx,ly,visited_cell,visited_ngh,res,obf_all,center_p,mapflag)
          
          
          lnext <- length(visited_ngh)
          i <- i +1
          if(l != lnext ){
            ln <- lnext-l
            il <- i +lnext-l-1
            visited_cell[i: il] <- visited_ngh[l:ln]
            i <- i+lnext-l
            l <- lnext
          }
          
        }
      ##  cell's bottom neighbor considering the cell bounders
      if (next_ind > res)
       if (!H$df.OId[next_ind -res] %in% visited_cell & H$df.Hvalue[next_ind -res ] != H$df.Hvalue[next_ind]+1 )
        ###//& H$df.Num[next_ind -res] > 0)
        if ((total_ply$numpoly < k & drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) <= area_bufk) 
            | drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) < trsh_area){
          totalk <- totalk +  H$df.Num[next_ind - res]
          visited_cell[i] <- H$df.OId[next_ind- res]
          ## print(paste('iii', i, 'obf_pcenter333',obf_p[i], 'numof point hilbert',H$df.Num[next_ind -res]))
          total_ply <- ply_numpolyg_obfpoly(area,H,pnt,total_ply,tag,visited_cell[i],
                                            lx,ly,visited_cell,visited_ngh,res,obf_all,center_p,mapflag)
          

          lnext <- length(visited_ngh)
          i <- i +1
          if(l != lnext ){
            ln <- lnext-l
            il <- i +lnext-l-1
            visited_cell[i: il] <- visited_ngh[l+1:ln]
            i <- i+lnext-l
            l <- lnext
          }
          
        }
      ##  cell's up neighbor considering the cell bounders
      if (next_ind + res < d)
       if (!H$df.OId[next_ind + res] %in% visited_cell & H$df.Hvalue[next_ind +res ] != H$df.Hvalue[next_ind]+1  )
        ###// & H$df.Num[next_ind +res ] > 0)
        if ((total_ply$numpoly < k & drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) <= area_bufk) 
            | drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) < trsh_area){
          totalk <- totalk +  H$df.Num[next_ind + res]
          visited_cell[i] <- H$df.OId[next_ind + res]
          
          ##  print(paste('iii', i, 'obf_pcenter444',obf_p[i], 'numof point hilbert',H$df.Num[next_ind + res]))
          total_ply <- ply_numpolyg_obfpoly(area,H,pnt,total_ply,tag,visited_cell[i],
                                            lx,ly,visited_cell,visited_ngh,res,obf_all,center_p,mapflag)
          
          
          lnext <- length(visited_ngh)
          i <- i +1
          if(l != lnext ){
            ln <- lnext-l
            il <- i +lnext-l-1
            visited_cell[i: il] <- visited_ngh[l+1:ln]
            i <- i+lnext-l
            l <- lnext
          }
        }
      ##  cell follows by Hilbert curve value order 
      next_Hv <- H$df.Hvalue[next_ind]+1 
      ## find the index of cell with following Hilbert value
      next_ind <- which(H$df.Hvalue == next_Hv)
      if (!H$df.OId[next_ind] %in% visited_cell )
        if ((total_ply$numpoly < k & drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) <= area_bufk) 
            | drop_units(st_area(st_buffer(total_ply$areapoly ,-pnt$maxd_edge[center_p]))) < trsh_area){
          totalk <- totalk +  H$df.Num[next_ind]
          visited_cell[i] <- H$df.OId[next_ind]
          total_ply <- ply_numpolyg_obfpoly(area,H,pnt,total_ply,tag,visited_cell[i],
                                            lx,ly,visited_cell,visited_ngh,res,obf_all,center_p,mapflag)
          
          lnext <- length(visited_ngh)
          i <- i +1
          if(l != lnext ){
            ln <- lnext-l
            il <- i +lnext-l-1
            visited_cell[i: il] <- visited_ngh[l+1:ln]
            i <- i+lnext-l
            l <- lnext
          }
        }
      if (!tag1 & total_ply$numpoly != num_poly){
        num_poly <- total_ply$numpoly
      }
    }
    ## obfuscated area
    total_ply$areapoly  <- st_buffer(total_ply$areapoly ,-(pnt$maxd_edge[center_p] +alpha1))
    ##  select random point as a obfuscated point in a obfuscated area
    rand_point <- st_sample(total_ply$areapoly, N)
    t <- st_geometry(rand_point)
    ixm <-whichmedian(st_distance(rand_point,center_lonlat))
    mdata$hoave_x[center_p] <- rand_point[[ixm]][1]
    mdata$hoave_y[center_p] <- rand_point[[ixm]][2]
    
    pnt$hoave_x[center_p] <- rand_point[[ixm]][1]
    pnt$hoave_y[center_p] <- rand_point[[ixm]][2]
    
    
    obf_all$geometry[[center_p]][1] <- rand_point[[ixm]][1]
    obf_all$geometry[[center_p]][2] <- rand_point[[ixm]][2]
    obf_all$plotUID[center_p] <- pnt$plotUID[center_p]
    ## generate a maximum obfuscated polygon (MOP) 
    tmp_poly <- st_buffer(obf_all$geometry[center_p],input_data$maxd_edge[center_p])
    if (tag1){
      tag1 <- FALSE
    }
    if (mapflag){
      plot(total_ply$areapoly$geometry,col= 'purple', add = TRUE) ## obfuscated area
      plot(tmp_poly, col = 'green', add = TRUE) ## MOP
      plot(pnt$geometry[center_p],col='red', add = TRUE, cex = 1,pch = '*') ## centroid of original polygon 
    }
  }
  print(Sys.time() - start_time)
  return(mdata)
}


#############################################################################################
## function ply_numpolyg_obfpoly returns number of complete polygons inside a given cell and its 8 neighbors
# and associated obfuscation area 
ply_numpolyg_obfpoly <- function(area,H,pnt,total_ply,tag,ii,lx,ly,obf_ii,visited_ngh,res, obf_all,cnt,mapflag){
  numpoly <- 0
  areapoly <- 0
  alpha <- 0.1
  np <- length(visited_ngh)   
  d <- res * res
  tmp_areapoly <- total_ply$areapoly
  tmp_grid <- ply_grid(H,lx,ly,ii) # generate cell ii in a Hilbert data structure
  st_crs(tmp_grid) <- st_crs(pnt)
  inter_grid_area <- st_intersection(area,tmp_grid)
  if (nrow(inter_grid_area) > 0 ){
    ## obtain number of points (centroid of polygons) inside a cell and add it to total number of points
    points_in_grid <- st_intersection(tmp_grid,pnt)  
    numpoly <- numpoly + nrow(points_in_grid) 
    ##  define 8 neighbors of a cell ii 
    ##  (left,upper left, up, upper right,right,lower right,bottom, lower left)
    tmp_ii <- c(ii-1,ii-1+res,ii+res,ii+1+res, ii+1,ii+1-res,ii -res,ii-1-res)
    if (nrow(points_in_grid) > 0 ){
      for(i in 1: nrow(points_in_grid)){
        tmp_shape <- readWKB( points_in_grid$plot_shape[i])   ## read each polygon with a given centroid
        tmp_shape <- SpatialPolygons(list(Polygons(list(tmp_shape@polygons[[1]]@Polygons[[1]]),ID=1)))
        tmp_shape <- st_as_sf(tmp_shape)
        st_crs(tmp_shape) <- st_crs(pnt)
        tmp_intersection <- st_intersection(tmp_grid,tmp_shape)
        if (i == 1){
          sensetive_area <- tmp_shape    ## at start sensitive area is the original polygon
          total_grid <- tmp_grid
        }
        else
          sensetive_area <- st_union(sensetive_area,tmp_shape)   ## add each polygon to sensitive area
        n <- 1
        while (drop_units(st_area(tmp_shape)) != drop_units(st_area(tmp_intersection)) & n <= 8){
          if (!tmp_ii[n] %in% obf_ii & !tmp_ii[n] %in% visited_ngh & 
              tmp_ii[n] < d & tmp_ii[n] > 0 & tmp_ii[n] %% res != 0 & tmp_ii[n] %% res != 1){
            
            tmp_grid_ii <- ply_grid(H,lx,ly,tmp_ii[n])
            st_crs(tmp_grid_ii) <- st_crs(pnt)
            tmp_inter_gridii <- st_intersection(tmp_grid_ii,tmp_shape)
            if (nrow(tmp_inter_gridii) > 0 &
                !tmp_ii[n] %in% obf_ii & !tmp_ii[n] %in% visited_ngh ){
              np <- np +1
              visited_ngh[np] <<- tmp_ii[n]
              total_grid <- st_union(total_grid,tmp_grid_ii)
              p_in_gridii <- st_intersection(tmp_grid_ii,pnt)
              if (nrow(p_in_gridii) > 0 ){
                for (inext in 1: nrow(p_in_gridii)){
                  tmp_shapeii <- readWKB( p_in_gridii$plot_shape[inext])
                  tmp_shapeii <- SpatialPolygons(list(Polygons(list(tmp_shapeii@polygons[[1]]@Polygons[[1]]),ID=1)))
                  tmp_shapeii <- st_as_sf(tmp_shapeii)
                  st_crs(tmp_shapeii) <- st_crs(pnt)
                  sensetive_area <- st_union(sensetive_area,tmp_shapeii)
                  numpoly <- numpoly + 1
                }#endfor
              }#enfif
            }#endif
          }#endif
          n <- n+1
        } # while end
      } #for end avali
      sensetive_area <- st_buffer(sensetive_area,alpha)
      obf_area <- st_difference(total_grid,sensetive_area)  ## remove sensitive area from obfuscated area
    } ## end if
    else{
      obf_area <- tmp_grid
      total_grid <- tmp_grid
    }
    if (tag){
      total_ply$numpoly <- total_ply$numpoly + numpoly
      if(nrow(obf_area) > 0 )
        total_ply$areapoly <- st_union(total_ply$areapoly ,obf_area)
    }
    else{
      total_ply$numpoly <- numpoly
      total_ply$areapoly <-  obf_area
      tag <<- TRUE
    }
    total_ply$areapoly <- st_intersection(area,total_ply$areapoly)
    ###############################################################################
    tmp_grid_buf <- st_buffer(total_grid,max(pnt$maxd_edge))
    obfp_in_grid <- st_intersection(tmp_grid_buf,obf_all)
    if (nrow(obfp_in_grid) > 0 ){
      for(iobf in 1: nrow(obfp_in_grid)){
        uid <- which(pnt$plotUID == obfp_in_grid$plotUID[iobf])
        tmp_obf <- st_buffer(obfp_in_grid$geometry[iobf],pnt$maxd_edge[uid]+ alpha)
        tmp_inter_obf <- st_intersection(total_grid,tmp_obf)
        if (nrow(tmp_inter_obf) > 0 ){
          total_ply$areapoly <- st_difference(total_ply$areapoly,tmp_inter_obf )
        }
      } #for end 
    } ## end if
    
  }  # end first if 
  if (mapflag)
     plot(total_ply$areapoly$geometry,col = 'yellow')  ## extended sensitive area
  return(total_ply)
}



##  example to plot obfuscated area 
Ntest <- plyst_grid_H_all_obfpoly(Corkt,orgmock_k1_5_k2_12_tmp,orgmock_k1_5_k2_12_tmp,8,5,1,3,5,TRUE,H8t)

orgmock_k1_5_k2_12_tmp <- plyst_grid_H_all_obfpoly(Corkt,orgmock_k1_5_k2_12_tmp,orgmock_k1_5_k2_12_tmp,8,5,1,nrow(orgmock_k1_5_k2_12_tmp),5,FALSE,H8t)

