# Data Preprocessing

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

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

sql = paste("SELECT homeTeam, awayTeam, homeScore, awayScore, hTeam.name as homeTeamName, aTeam.name as awayTeamName, (SELECT AVG(homeScore) FROM SoccerResults WHERE gameDate < sr.gameDate AND homeTeam = sr.homeTeam ) AS avgHomeScore, (SELECT AVG(awayScore) FROM SoccerResults WHERE gameDate < sr.gameDate AND awayTeam = sr.awayTeam ) AS avgAwayScore,(homeScore - awayScore) as result FROM `SoccerResults` sr INNER JOIN Team hTeam ON homeTeam = hTeam.id INNER JOIN Team aTeam ON awayTeam = aTeam.id AND sr.leagueId = (SELECT id FROM League where name = '",
            league,
            "' AND countryId = (SELECT id FROM Country WHERE name = '",
            country,
            "')) ORDER BY sr.gameDate ASC", 
            sep = "", collapse = "")


piSql = paste("SELECT homeTeam, awayTeam, homeScore, awayScore, hTeam.name as homeTeamName, aTeam.name as awayTeamName, (SELECT AVG(homeScore) FROM SoccerResults WHERE gameDate < sr.gameDate AND homeTeam = sr.homeTeam ) AS avgHomeScore, (SELECT AVG(awayScore) FROM SoccerResults WHERE gameDate < sr.gameDate AND awayTeam = sr.awayTeam ) AS avgAwayScore FROM `SoccerResults` sr INNER JOIN Team hTeam ON homeTeam = hTeam.id INNER JOIN Team aTeam ON awayTeam = aTeam.id WHERE sr.leagueId = (SELECT id FROM League where name = '",
              league,
              "' AND countryId = (SELECT id FROM Country WHERE name = '",
              country,
              "')) ORDER BY sr.gameDate ASC", 
              sep = "", collapse = "")

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')

