library(data.table)

print("Reading data")
train <- fread('../input/train.csv', 
               select = c('Semana','Cliente_ID', 'Producto_ID', 'Agencia_ID', 'Ruta_SAK', 'Demanda_uni_equil'))

test <- fread('../input/test.csv', 
              select = c('id','Semana', 'Cliente_ID', 'Producto_ID', 'Agencia_ID', 'Ruta_SAK'))

week6_dataSet <- subset(train, train$Semana == 6)
week7_dataSet <- subset(train, train$Semana == 7)
#print(week_dataSet)

#Find means of demand for each product
week6_mean_D <- week6_dataSet[, .(MD = mean(Demanda_uni_equil)), by = .(Producto_ID)]
week7_mean_D <- week7_dataSet[, .(MD = mean(Demanda_uni_equil)), by = .(Producto_ID)]
total_mean_D  <- train[, .(MD = mean(Demanda_uni_equil)), by = .(Producto_ID)]
#print(week6_mean_D)

week_10 <- subset(test, test$Semana == 10)
week_11 <- subset(test, test$Semana == 11)

submit1 <- merge(week_10, week6_mean_D, all.x = TRUE, by = "Producto_ID")
submit2 <- merge(week_11, week7_mean_D, all.x = TRUE, by = "Producto_ID")
train   <- merge(train, total_mean_D, all.x = TRUE, by = "Producto_ID");

submit1$Demanda_uni_equil <- submit1$MD
submit2$Demanda_uni_equil <- submit2$MD

submit1[is.na(Demanda_uni_equil)]$Demanda_uni_equil <- train$MD 
submit2[is.na(Demanda_uni_equil)]$Demanda_uni_equil <- train$MD 

print(submit1)
print(submit2)

new <- rbind(submit1, submit2)
print(new)

print("Write output file")
#write the output into a csv file
write.csv(new[,.(id,Demanda_uni_equil)],"output_prediction_based_on_week6_7.csv", row.names = FALSE)
print("Done!")