library(dplyr)
library(readr)
library(ggplot2)
library(ggrepel)

gc()
state = "nt"

source("htv_abbrevs.R")
if (state %in% c("act", "nt")) {
  alp_htv = alp_htv[1:3]
  lib_htv = lib_htv[1:3]
}

png_print = function(out_file, img_width, img_height, ggplot_img) {
  # A function to print a plot to png:
  png(filename=out_file, width=img_width, height=img_height, units="px")
  print(ggplot_img)
  dev.off()
  return(TRUE)
}

in_file = sprintf("atl_votes_%s.csv", state)
prefs.df = read_csv(in_file)

pref_pca = prcomp(prefs.df, scale. = TRUE)

pca_evals = pref_pca$sdev^2
pca_evals_cumul = cumsum(pca_evals)
fraction_variance = pca_evals_cumul / sum(pca_evals)

pca.df = as.data.frame(pref_pca$rotation)
pca.df$name = row.names(pca.df)
pca.df$ALP_HTV = ""
pca.df$Lib_HTV = ""

pca.df$ALP_HTV[which(pca.df$name %in% alp_htv)] = "ALP"
pca.df$Lib_HTV[which(pca.df$name %in% lib_htv)] = "Lib"

pca.df$HTV = sprintf("%s%s", pca.df$ALP_HTV, pca.df$Lib_HTV)
pca.df$HTV = gsub("ALPLib", "Both", pca.df$HTV)
pca.df$HTV[which(pca.df$HTV == "")] = "Neither"

ALP_i = which(pca.df$name == "ALP")
LNP_i = which(pca.df$name == lib_abbrev)
PHON_i = which(pca.df$name == phon_rua)

if (pca.df$PC1[ALP_i] > pca.df$PC1[LNP_i]) {
  pca.df$PC1 = -pca.df$PC1
}

if (pca.df$PC2[PHON_i] < 0) {
  pca.df$PC2 = -pca.df$PC2
}

title_str = sprintf("PCA: %s ATL preferences", state_title)
out_file_png = sprintf("images/pca/%s_pc1_pc2.png", state)
out_file_variance = sprintf("pca_data/%s_fraction_variance.txt", state)
out_file_pca = sprintf("pca_data/%s_df.Rda", state)

htv_colours = c(ALP = "#FF0000", Lib = "#0000FF", Both = "#800080", Neither = "#000000")

circle_plot = ggplot(data=pca.df) +
  geom_point(aes(x=PC1, y=PC2, colour=factor(HTV))) +
  geom_text_repel(aes(x=PC1, y=PC2, label=name, colour=factor(HTV)), size=6, show.legend=FALSE) +
  scale_color_manual(values=htv_colours, name="HTV cards") +
  theme_grey(base_size = 16) +
  guides(colour = guide_legend(override.aes = list(size=4))) +
  theme(legend.text=element_text(size=16)) +
  ggtitle(title_str)

write(fraction_variance, file=out_file_variance, ncolumns = 1)
save("pca.df", file=out_file_pca)

png_print(out_file_png, 600, 500, circle_plot)
print(circle_plot)
