# Dados fornecidos na questão
clock <- c(0.1, 0.5, 1, 1.5, 2, 2.5, 3)
MRT_1F <- c(517.1468515630205, 85.13094142168089, 30.333207896694553, 12.694776264558937, 3.3041601673945418, 1.1823111717498882, 1.1892293502386786)
MRT_3F <- c(156.68929936163462, 11.540837783562276, 0.4512835621696538, 0.4509797929766453, 0.4502068233039181, 0.4496185276300172, 0.4543157082191288)
MRT_5F <- c(83.90319666471157, 0.3068151086494968, 0.30522314133037304, 0.3072588968084928, 0.30655265997285697, 0.3055812715727718, 0.3053297166713006)
MRT_10F <- c(29.55430642951759, 0.19832832665772515, 0.1971923924717474, 0.19796648905716516, 0.19615594370806338, 0.2034569237883263, 0.19617420889447737)
MRT_15F <- c(11.317736530583566, 0.167364215666193, 0.16172168266811013, 0.16701085329580515, 0.1598052657153692, 0.1645934043532696, 0.16216563797118075)
MRT_sem_F <- c(11.93430909937736, 0.6095414637034009, 0.6060645101029295, 0.612167181646899, 0.6146761002685637, 0.6096747087200697, 0.6125810476877268)

# Configuração do Layout
layout(matrix(c(1,1, 2,3, 4,5, 6,6), nrow = 4, ncol = 2, byrow = TRUE), heights = c(2, 1, 1, 1))

# Reduzir as margens dos gráficos para caber no painel (abaixo, esquerda, acima, direita)
par(mar = c(3.5, 3.5, 2, 1))

# 1. Gráfico Principal de Linhas
plot(clock, MRT_1F, type = "b", pch = 4, col = "black",
     xlab = "Time between Things requests (seconds)", ylab = "Response Time (sec.)",
     ylim = c(0, 520))
lines(clock, MRT_3F, type = "b", pch = 15, col = "gold")
lines(clock, MRT_5F, type = "b", pch = 17, col = "pink")
lines(clock, MRT_10F, type = "b", pch = 18, col = "purple")
lines(clock, MRT_15F, type = "b", pch = 25, col = "cyan")
lines(clock, MRT_sem_F, type = "b", pch = 19, col = "forestgreen")
legend("topright", legend = c("1 Fog", "3 Fogs", "5 Fogs", "10 Fogs", "15 Fogs", "w/o Fog"),
       col = c("black", "gold", "pink", "purple", "cyan", "forestgreen"),
       pch = c(4, 15, 17, 18, 25, 19), lty = 1, cex = 0.8)

# 2. Gráficos de barras comparativos com escala logarítmica
fogs_list <- list("1 Fog" = MRT_1F, "3 Fogs" = MRT_3F, "5 Fogs" = MRT_5F, "10 Fogs" = MRT_10F, "15 Fogs" = MRT_15F)
for(nome in names(fogs_list)) {
  mat <- rbind(MRT_sem_F, fogs_list[[nome]])
  barplot(mat, beside = TRUE, log = "y", col = c("#E6E6E6", "#666666"),
          names.arg = clock, xlab = "Time between Things requests", ylab = "Response time (s)")
  legend("topright", legend = c("w/o Fog", nome), fill = c("#E6E6E6", "#666666"), cex = 0.7)
}

# Matriz da qualidade de refeições por faixas de preço
dados_refeicao <- matrix(
  c(53.8, 54.2, 11.9,
    33.9, 43.6, 2.6,
    2.6, 60.5, 36.8,
    0.0, 21.4, 78.6),
  nrow = 3, byrow = FALSE,
  dimnames = list(c("Good", "Very Good", "Excellent"),
                  c("$10-19", "$20-29", "$30-39", "$40-49"))
)

# Gráfico de barras empilhadas
barplot(dados_refeicao, beside = FALSE,
        col = c("#7FA9C0", "#E39B64", "#85C17E"),
        main = "Qualidade da Refeição por Faixa de Preço",
        xlab = "Preço da Refeição", ylab = "Percentagem (%)")
legend("topright", legend = rownames(dados_refeicao),
       fill = c("#7FA9C0", "#E39B64", "#85C17E"), title = "Qualidade")

# Conversão de temperaturas do mês de Maio de Fahrenheit para Celsius
temp_maio_F <- airquality$Temp[airquality$Month == 5]
temp_maio_C <- (temp_maio_F - 32) / 1.8

# Histograma com curva de densidade
hist(temp_maio_C, freq = FALSE, col = "lightblue",
     main = "Distribuição de Temperaturas no Mês de Maio",
     xlab = "Temperatura (°C)", ylab = "Densidade")
lines(density(temp_maio_C), col = "red", lwd = 2)

# Leitura segura dos dados de vendas
url_sales <- "[https://www.dropbox.com/scl/fi/mpjt4uuqb5vtmfiw38phk/Sales.txt?rlkey=93jlz79xwrrt7ah66d5k403d7&dl=1](https://www.dropbox.com/scl/fi/mpjt4uuqb5vtmfiw38phk/Sales.txt?rlkey=93jlz79xwrrt7ah66d5k403d7&dl=1)"

sales <- tryCatch({
  if (file.exists("Sales.txt")) {
    read.table("Sales.txt", header = TRUE)
  } else {
    read.table(url_sales, header = TRUE)
  }
}, error = function(e) {
  # Tentar baixar arquivo diretamente se a leitura via URL falhar
  download.file(url_sales, destfile = "Sales.txt", quiet = TRUE)
  read.table("Sales.txt", header = TRUE)
})

# Identificar colunas independentemente de letras maiúsculas/minúsculas
col_sales <- grep("sales", colnames(sales), ignore.case = TRUE, value = TRUE)[1]
col_country <- grep("country", colnames(sales), ignore.case = TRUE, value = TRUE)[1]

if (!is.na(col_sales) && !is.na(col_country)) {
  totais_vendas <- tapply(sales[[col_sales]], sales[[col_country]], sum)
  percentagens <- round(100 * totais_vendas / sum(totais_vendas), 1)
  labels_pie <- paste0(percentagens, "%")
  cores <- rainbow(length(totais_vendas))

  pie(totais_vendas, labels = labels_pie, col = cores,
      main = "Porcentagem do Total de Vendas por País")
  legend("topright", legend = names(totais_vendas), fill = cores, cex = 0.8)
} else {
  warning("Não foi possível carregar as colunas de vendas corretamente.")
}

# Boxplot do dataset InsectSprays sem presença de outliers
boxplot(count ~ spray, data = InsectSprays,
        outline = FALSE, col = "yellow",
        main = "Contagem de Insetos por Tipo de Inseticida",
        xlab = "Tipo de Inseticida (Spray)", ylab = "Contagem de Insetos")

# Função para converter o texto de memória utilizada para Megabytes (MB)
converter_para_mb <- function(vetor_memoria) {
  sapply(vetor_memoria, function(val) {
    num <- as.numeric(gsub("[^0-9.]", "", val))
    unidade <- toupper(gsub("[^A-Za-z]", "", val))
    if (grepl("TB", unidade)) return(num * 1000000)
    if (grepl("GB", unidade)) return(num * 1024)
    if (grepl("KB", unidade)) return(num / 1024)
    return(num)
  })
}

# Leitura e processamento dos arquivos CSV de monitoramento
ficheiros <- c("monitoringCloudData_NONE.csv", "monitoringCloudData_0.1.csv",
               "monitoringCloudData_0.5.csv", "monitoringCloudData_1.csv")
titulos <- c("Memory Analysis (None Workload)", "Memory Analysis (Workload of 0.1)",
             "Memory Analysis (Workload of 0.5)", "Memory Analysis (Workload of 1.0)")

layout(matrix(1:4, nrow = 2, ncol = 2, byrow = TRUE))

for(i in 1:length(ficheiros)) {
  if (file.exists(ficheiros[i])) {
    df <- read.csv(ficheiros[i])
    tempo_horas <- as.numeric(difftime(as.POSIXct(df$currentTime), as.POSIXct(df$currentTime[1]), units = "hours"))
    memoria_mb <- converter_para_mb(df$usedMemory)
    
    plot(tempo_horas, memoria_mb, type = "l",
         main = titulos[i], xlab = "Time (hour)", ylab = "Used Memory (MB)")
  } else {
    plot(1, type = "n", main = paste("Arquivo não encontrado:", ficheiros[i]))
  }
}

## Questão 7
# Leitura da base de dados da Netflix (Local ou URL)
if (file.exists("netflix_titles.csv")) {
  netflix <- read.csv("netflix_titles.csv")
} else {
  netflix <- read.csv("[https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-20/netflix_titles.csv](https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-20/netflix_titles.csv)")
}

# Filtrar apenas 1 país de origem e obter os Top 10
top10_paises <- netflix %>%
  filter(!is.na(country) & country != "" & !grepl(",", country)) %>%
  count(country, sort = TRUE) %>%
  head(10)

# Gráfico de pizza com chamada explícita de p7
p7 <- plot_ly(top10_paises, labels = ~country, values = ~n, type = 'pie') %>%
  layout(title = 'Top 10 Países com Mais Conteúdo na Netflix')
p7
# Tabela estilizada com Plotly
p8 <- plot_ly(
  type = 'table',
  header = list(
    values = c('<b>País</b>', '<b>Total de conteúdos</b>'),
    fill = list(color = 'gray'),
    font = list(color = 'white', size = 12),
    align = 'center'
  ),
  cells = list(
    values = rbind(top10_paises$country, top10_paises$n),
    align = 'center'
  )
)
p8
# Agrupamento por década e tipo de conteúdo
netflix_decadas <- netflix %>%
  filter(!is.na(release_year)) %>%
  mutate(decada = (release_year %/% 10) * 10) %>%
  group_by(decada, type) %>%
  summarise(qtd = n(), .groups = 'drop')

df_filmes <- netflix_decadas %>% filter(type == "Movie")
df_series <- netflix_decadas %>% filter(type %in% c("TV Show", "TV Series"))

# Gráfico de linhas com Plotly
p9 <- plot_ly() %>%
  add_trace(data = df_series, x = ~decada, y = ~qtd, name = 'TV Series',
            type = 'scatter', mode = 'lines+markers', line = list(color = 'blue')) %>%
  add_trace(data = df_filmes, x = ~decada, y = ~qtd, name = 'Movies',
            type = 'scatter', mode = 'lines+markers', line = list(color = 'orange')) %>%
  layout(title = 'Quantidade de Conteúdo por Década',
         xaxis = list(title = 'Década'),
         yaxis = list(title = 'Qnd. Conteúdo'))
p9
# Filtrar filmes lançados entre 2000 e 2010 pelos gêneros especificados
filmes_genero <- netflix %>%
  filter(type == "Movie", release_year >= 2000, release_year <= 2010) %>%
  mutate(genero_principal = trimws(sub(",.*", "", listed_in))) %>%
  filter(genero_principal %in% c("Dramas", "Action & Adventure", "Comedies")) %>%
  group_by(release_year, genero_principal) %>%
  summarise(qtd = n(), .groups = 'drop')

# Gráfico de barras lado a lado com Plotly
p10 <- plot_ly(filmes_genero, x = ~release_year, y = ~qtd, color = ~genero_principal, type = 'bar') %>%
  layout(barmode = 'group',
         title = 'Quantidade de Filmes Lançados por Gênero (2000-2010)',
         xaxis = list(title = 'Ano de Lançamento', tickmode = 'linear', dtick = 1),
         yaxis = list(title = 'Qnt. de Lançamentos'))
p10