# This R environment comes with all of CRAN preinstalled, as well as many other helpful packages
# The environment is defined by the kaggle/rstats docker image: https://github.com/kaggle/docker-rstats
# For example, here's several helpful packages to load in 

library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

system("ls ../input")

# Any results you write to the current directory are saved as output.

wkt = read.csv('../input/train_wkt_v3.csv', colClasses=c('character','NULL','NULL'))
# wkt[wkt[,3]=='MULTIPOLYGON EMPTY',3] = NA

col0 = rainbow(n=10, alpha = .5)


# library(rgeos)
# library(raster)
# for(img in 1:25) {
  # print(as.character(unique(wkt$ImageId)[img]))
  # png(paste0(unique(wkt$ImageId)[img],".png"), width=2*480)
  # par(mfrow=c(1,2))
  # imgs <- stack(paste0("../input/three_band/", unique(wkt$ImageId)[img],".tif"))
  # plotRGB(imgs, stretch = "lin")
  
  # k = j = 1
  # for(i in (wkt[(img-1)*10+1:10,3])) {
    # if(!is.na(i)) {
      # plot(readWKT(i), add=ifelse(j==1, F, T), col=k, main=as.character(unique(wkt$ImageId)[img])) # R only has 8 colors by default
      # j = j + 1
    # }
    # k = k + 1
  # }
  # dev.off()
# }

# use the correct geojson instead

filename_to_classType = as.data.frame(matrix(c(
  '001_MM_L2_LARGE_BUILDING',1,
  '001_MM_L3_RESIDENTIAL_BUILDING',1,
  '001_MM_L3_NON_RESIDENTIAL_BUILDING',1,
  '001_MM_L5_MISC_SMALL_STRUCTURE',2,
  '002_TR_L3_GOOD_ROADS',3,
  '002_TR_L4_POOR_DIRT_CART_TRACK',4,
  '002_TR_L6_FOOTPATH_TRAIL',4,
  '006_VEG_L2_WOODLAND',5,
  '006_VEG_L3_HEDGEROWS',5,
  '006_VEG_L5_GROUP_TREES',5,
  '006_VEG_L5_STANDALONE_TREES',5,
  '007_AGR_L2_CONTOUR_PLOUGHING_CROPLAND',6,
  '007_AGR_L6_ROW_CROP',6, 
  '008_WTR_L3_WATERWAY',7,
  '008_WTR_L2_STANDING_WATER',8,
  '003_VH_L4_LARGE_VEHICLE',9,
  '003_VH_L5_SMALL_VEHICLE',10,
  '003_VH_L6_MOTORBIKE',10), ncol=2, byrow=T))
filename_to_classType$V1 = as.character(filename_to_classType$V1)
filename_to_classType$V2 = as.numeric(as.character(filename_to_classType$V2))

grid = read.csv('../input/grid_sizes.csv')

library(geojsonio)
library(raster)
library(rgdal)
for(img in unique(wkt$ImageId)) {
  print(img)
  png(paste0(img,".png"), width=2*480)
  grid0 = as.vector(as.matrix(grid[grid$X==img,-1]))
  # print(grid0)
  
  par(mfrow=c(1,2))
  imgs <- stack(paste0("../input/three_band/", img,".tif"))
  plotRGB(imgs, stretch = "lin")
  
  j = 1
  for(i in 1:10) {
    class = filename_to_classType[filename_to_classType[,2]==i, 1]
    file00 = NULL
    for(cl in class) file00 = c(file00, dir(pattern=cl, path=paste0('../input/train_geojson_v3/', img), full.names = T))
    if(length(file00)!=0) {
      for(file0 in file00) {
        if(file0 != "../input/train_geojson_v3/6100_2_3/001_MM_L5_MISC_SMALL_STRUCTURE.geojson") 
        plot(geojson_read(file0, what= 'sp'), add=ifelse(j==1, F, T), col=col0[i], xlim=c(0, grid0[1]),
        ylim=c(grid0[2],0)) else plot(readOGR(file0, require_geomType='wkbPolygon'), add=ifelse(j==1, F, T), 
        col=col0[i], xlim=c(0, grid0[1]), ylim=c(grid0[2],0))
        j = j + 1
      }
    }
  }
  dev.off()
}

png('legend.png')
barplot(1:10,col=col0[1:10])
legend('topleft', legend=c('1 building','2 small struct', '3 good roads',
                           '4 track/trial','5 VEG','6 ARG','7 Waterway','8 water',
                           '9 large vh','10 small vh'),pch=15,col=col0[1:10])
dev.off()
