---
title: GraphTV
runtime: shiny
output:
  html_document
---

```{r setup, message = F, warning = F, echo = F}
library(tidyverse)
library(httr)
library(rvest)
library(plotly)
library(jsonlite)
library(knitr)

opts_chunk$set(message = F,
               echo = F,
               warning = F)

key <- "?api_key=32e0ed1416c58777f986f3f33751fc22"
tmdb_url <- "http://api.themoviedb.org/3/"
```

```{r input}
inputPanel(
  textInput("show_search", "Search show"),
  actionButton("button_search", "Search show"),
  uiOutput("show_choice")
)

shows <- eventReactive(input$button_search, {
    req(input$show_search)

    serie <- input$show_search %>% url_escape

    GET(str_c(tmdb_url, "search/tv", key, "&query=", serie)) %>%
      content(as = "text") %>%
      fromJSON -> res

    #res$results$poster_path

    res$results$id %>%
      as.list %>%
      setNames(res$results$original_name)
})

output$show_choice <- renderUI({
  req(shows())

  selectizeInput("show", "Please choose…", shows())
})
```

```{r graph}
renderPlotly({
  req(input$show)

  show_id <- input$show

  GET(str_c(tmdb_url, "tv/", show_id, key)) %>%
    content(as = "text") %>%
    fromJSON -> res

  res$backdrop_path
  1:res$number_of_seasons -> seasons
  res$vote_average

  seasons %>%
    map(~ GET(str_c(tmdb_url, "tv/", show_id, "/season/", ., key)) %>%
        content(as = "text") %>%
        fromJSON) -> res

  res %>%
    map("episodes") %>%
    reduce(bind_rows) %>%
    select(season_number, episode_number, name, still_path, vote_average) -> episodes

  episodes %>%
    by(.$season_number, function(x){
         fit <- lm(vote_average ~ episode_number, data = x)
         x %>%
           plot_ly(hoverinfo = "text",
                   text = ~str_c("S", season_number, "E", episode_number, " - ", name, "<br>",
                                 "Rating: ", vote_average, "<br>")) %>%
         add_trace(data = x, x = ~episode_number, y = ~vote_average, mode = "markers") %>%
         add_trace(data = x, x = ~episode_number, y = fitted(fit), mode = "lines") %>%
         layout(xaxis = list(tick0 = 0, dtick = 1),
                yaxis = list(title = "Rating"))
        }) %>%
  subplot(shareY = T, nrows = 1) %>%
  hide_legend
})
```
