#Heatmaps Preps

packages<-c('ggplot2','reshape','gdata','lubridate', 'dplyr','sf','adehabitatHR','spatialEco','raster','stringi')

package.check <- lapply(packages, FUN = function(x) {
  if (!require(x, character.only = TRUE)) {
    install.packages(x, dependencies = TRUE)
    library(x, character.only = TRUE)
  }
})


rm(list=ls()) ## Removendo as variáveis
gc()

#Loading mask raster layer
sbs<-raster('input_data/sbs_cs.tif')
zee.r<-aggregate(sbs,fact=10)
res(zee.r)


#Setting speed and depth tresholds
mod<-c('Armadilha','Arrasto','Emalhe','Espinhel')
l<-data.frame(mod)
l$vmin<-c(2,1,2,2)
l$vmax<-c(4,5,5,4)
l$pmin<-c(-80,-80,-5000,-5000)
l$pmax<-c(-30,-5,-70,-100)
l

#Zerando antes do loop
kde_all<-zee.r
log_all<-c('mod',0,0)

load('output_data/preps_aggh_SE_S.Rda')
dh<-dh%>%filter(lat<=-22.5 & lon<=-41)
i=1

for(i in 1:nrow(l)){
  time1<-Sys.time()
  df<-dh%>%filter(modalidade==l$mod[i])
  gc()
  df<-df%>%filter(vel<=l$vmax[i], vel>=l$vmin[i],prof<=l$pmax[i],prof>=l$pmin[i])
  df<-df[complete.cases(df),]
  xy<-df[,c('lon','lat')]
  spdf <- SpatialPointsDataFrame(coords = xy, data = df,
                                 proj4string = CRS("+init=epsg:4326"))
  # plot(spdf)
  kde<-sp.kde(spdf,y=1,bw=.4,newdata = zee.r, standardize = F)
  kde<-raster::resample(kde,sbs)*sbs
  # plot(kde)
  #Write raster
  writeRaster(kde,paste0('output_data/kde_sbs_',l$mod[i],'.tif'),overwrite=T)
  
  #Get number of hours and vessels
  log<-c(l$mod[i],nrow(df),length(unique(df$cod_embarcacao)))
  log_all<-rbind(log_all,log)
  print(i)
  print(l$mod[i])
  print(Sys.time()-time1)
  rm(df,spdf,xy,kde,log)
  gc()
}
# plot(kde_all)

save(log_all, file='output_data/kde_log_sbs.Rda')
