# Data Preprocessing

# Importing the Dataset
library(RMySQL)
mydb = dbConnect(MySQL(), user="atg", password="CvWKY34DqtlVgjt_9", host="nordh.xyz", dbname="atg")

sqlRacesWithEnoughParticipants = "SELECT raceNumber, raceDate, Result FROM `Results` group BY RaceDate, RaceNumber HAVING count(RaceNumber) > 5 AND Result = 1  
ORDER BY `Results`.`raceDate` DESC"

# With AVG per distance
newSql = "SELECT r1.*, ROUND(AVG(horseResults.time),4) as HorseAvgTime, ROUND(AVG(driverResults.time),4) as driverAvgTime, ROUND(AVG(IF(horseResults.Distance = r1.Distance, horseResults.time, null)),4) as driverAvgTime, ROUND(AVG(IF((horseResults.Distance = r1.Distance AND horseResults.Time > 0), horseResults.time, null)),4) as horseAvgByDistance, ROUND(AVG(IF((driverResults.Distance = r1.Distance AND driverResults.Time > 0), driverResults.time, null)),4) as driverAvgByDistance FROM Results r1 INNER JOIN Results horseResults ON r1.RaceDate > horseResults.RaceDate AND r1.HorseId = horseResults.HorseId INNER JOIN Results driverResults ON r1.RaceDate > driverResults.RaceDate AND r1.DriverId = driverResults.DriverId WHERE r1.raceNumber = 10 AND r1.RaceDate = '2021-02-08' GROUP BY r1.horseId"
newRs = dbSendQuery(mydb, newSql)
newRes = fetch(newRs, -1)

"WITH avg times" 
"SELECT r1.*, ROUND(AVG(if (horseResults.time > 0, horseResults.time,null)),4) as HorseAvgTime, ROUND(AVG(IF((horseResults.Distance = r1.Distance AND horseResults.Time > 0), horseResults.time, null)),4) as horseAvgByDistance FROM Results r1 INNER JOIN Results horseResults ON r1.RaceDate > horseResults.RaceDate AND r1.HorseId = horseResults.HorseId INNER JOIN Results driverResults ON r1.RaceDate > driverResults.RaceDate AND r1.DriverId = driverResults.DriverId WHERE r1.raceNumber = 10 AND r1.RaceDate = '2021-02-08' GROUP BY r1.horseId"

sqlForVoltStartLaneDistribution = "SELECT Lane, SUM(result)/Count(*), Count(*) as cnt FROM `Results` WHERE Result > 0 AND Lane > -1 AND TimeModifier NOT like "%a%" GROUP BY Lane HAVING cnt > 20 ORDER BY `SUM(result)/Count(*)` ASC"
sqlForAutoStartLaneDistribution = "SELECT Lane, SUM(result)/Count(*), Count(*) as cnt FROM `Results` WHERE Result > 0 AND Lane > -1 AND TimeModifier like "%a%" GROUP BY Lane HAVING cnt > 20 ORDER BY `SUM(result)/Count(*)` ASC"

country = 'iran'
league = 'persian-gulf-pro-league'

rs = dbSendQuery(mydb, sql)

dataset = fetch(rs, n=-1)

###Taking case of missing data
dataset$avgHomeScore = ifelse(is.na(dataset$avgHomeScore), 0, dataset$avgHomeScore)
dataset$avgAwayScore = ifelse(is.na(dataset$avgAwayScore), 0, dataset$avgAwayScore)
#dataset$avgHomeScoreOneYearBack = ifelse(is.na(dataset$avgHomeScoreOneYearBack), 0, dataset$avgHomeScoreOneYearBack)
#dataset$avgAwayScoreOneYearBack = ifelse(is.na(dataset$avgAwayScoreOneYearBack), 0, dataset$avgAwayScoreOneYearBack)

# Encoding categorical data
##dataset$overtime = factor(dataset$overtime, levels = c('1-0', '0-1', 'NULL'), labels = c(1, 1, 0))
##dataset$result = factor(dataset$result, levels = c('1', 'X', '2'), labels = c(1, 0, 2))


library(piratings)

rs2 = dbSendQuery(mydb, piSql)

piDataset = fetch(rs2, n=-1)

teams <- as.matrix(piDataset[,c("homeTeamName", "awayTeamName")])
outcomes <- as.matrix(piDataset[, c("homeScore", "awayScore")])

# England - premiere League seq(0.06, 0.1, 0.005), seq(0.4, 0.9, 0.05)
grid <- optimize_pi_ratings(teams, outcomes, seq(0.04, 0.1, 0.005), seq(0.3, 0.9, 0.05))

colnames(grid)[1] <- "rating"
gridOrdered = grid[order(grid$rating),]
bestRes = head(gridOrdered,1)

library(ggplot2)

# midpoint England Premier-league 2.9
# midpoint china Super-league 2.7
# midpoint sweden Allsvenskan 2.8
print("ggplot")
ggplot(data = grid, aes(x = lambda, y = gamma, fill = rating)) + 
  geom_tile() + scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 2.7) + 
  labs(x = "lambda", y = "gamma", title = "grid optimization", fill = "Mean \nsquared \nerror") + 
  theme(plot.title = element_text(hjust = 0.5))


# outcomes <- rbind(outcomes, c(0,0))
# teams <- rbind(teams, c("Wolves", "Southampton"))

# England 0.07, 0.7
# China Super-league 0.07, 0.5
# Sweden allsvenskan 0.075, 0.7
pratings <- calculate_pi_ratings(teams, outcomes, bestRes$lambda, bestRes$gamma)


print(tail(pratings, n = 15))

# newDataset = dataset
newDataset = piDataset
newDataset = cbind(piDataset, pratings)

colnames(newDataset)[9] <- "piOne"
colnames(newDataset)[10] <- "piTwo"


#test = cbind(dataset, pratings)
#colnames(test)[10] <- "piOne"
#colnames(test)[11] <- "piTwo"

round_df <- function(df, digits) {
  nums <- vapply(df, is.numeric, FUN.VALUE = logical(1))
  
  df[,nums] <- round(df[,nums], digits = digits)
  
  (df)
}

test = round_df(newDataset, digits = 3)

test2 <- transform(test, piRes=test$piOne - test$piTwo)
test2 <- transform(test2, bothSame=ifelse(test2$piRes > 0 & test2$avgHomeScore - test2$avgAwayScore > 0,TRUE,
                                          ifelse(test2$piRes < 0 & test2$avgHomeScore - test2$avgAwayScore < 0, TRUE, 
                                                 FALSE)))

test2 <- transform(test2, correct=ifelse(test2$homeScore > test2$awayScore & test2$bothSame & test2$piRes > 0, TRUE,
                                         ifelse(test2$homeScore < test2$awayScore & test2$bothSame & test2$piRes < 0, TRUE,
                                                FALSE)))

correct = test2[test2$correct == TRUE,]

notSame = test2[test2$bothSame == FALSE,]

draws = test2[test2$homeScore - test2$awayScore == 0,]

drawsDiff = draws[draws$piRes < 0.09 & draws$piRes > -0.09,]

### Regressor/ prediction thing

# Splitting the dataset into the Training set and Test set
# install.packages('caTools')
#library(caTools)
#set.seed(1111)
# split = sample.split(dataset$result, SplitRatio = 0.8)

smp_size <- floor(0.75 * nrow(newDataset))
train_ind <- sample(seq_len(nrow(newDataset)), size = smp_size)
train <- newDataset[1:smp_size,]
test <- newDataset[smp_size:nrow(newDataset), ]

smp_size <- floor(0.75 * nrow(test2))
train_ind <- sample(seq_len(nrow(test2)), size = smp_size)
train <- test2[1:smp_size,]
test <- test2[smp_size:nrow(test2), ]



# training_set = subset(dataset, split == TRUE)
# test_set = subset(dataset, split == FALSE)


# Feature scaling
#training_set[,6:7] = scale(training_set[,6:7])
#training_set[,9:11] = scale(training_set[,9:11])
#test_set[,6:7] = scale(test_set[,6:7])
#test_set[,9:11] = scale(test_set[,9:11])

regressor = lm(formula = result ~ avgHomeScore + avgAwayScore + piOne + piTwo + piRes,
               data = train)

y_pred = predict(regressor, newdata = test)


## Plot the result (probably not working)
#library(ggplot2)
#ggplot() +
#  geom_point(aes(x = train$avgHomeScore, y = train$result), 
#             colour = 'red') + 
#  geom_line(aes(x = train$avgHomeScore, y = predict(regressor, newdata = train)),
#            colour = 'blue') + 
#  ggtitle('Result plot') + 
#  xlab('Awarage Home Score') + 
#  ylab('result')

