class TeamsController < ApplicationController
  require 'nokogiri'
  require 'open-uri'
  require 'json'

  include ActionView::Helpers::SanitizeHelper

  before_action :set_team, only: %i[ show edit update destroy ]

  # GET /teams or /teams.json
  def index
    @teams = Team.all
  end

  # GET /teams/1 or /teams/1.json
  def show
  end

  # GET /teams/new
  def new
    @team = Team.new
    @team.categoryID = 124
    @team.teamID = 5251
  end

  # GET /teams/1/edit
  def edit
  end

  # GET /teams/1/update_players
  def update_team_info
    team = Team.find(params[:id])
    url = "https://padel.cjimenez.org/#{team.teamID}.html"
    #url = "https://www.fmpadel.com/ligas_verEquipos.aspx?idCategoria=#{team.categoryID}&idEquipo=#{team.teamID}"
    html = Nokogiri::HTML(URI.open(url))
    players = html.xpath('//div[@class = "row col-12"]/div[@class = "table-responsive"]/table/tbody/tr')
    players.each do |player_info|
      data = player_info.css('td')
      player_info_url = data[1].children[0].attribute_nodes[0].value
      name = data[2].inner_html
      last_name = "#{data[3].inner_html} #{data[4].inner_html}"
      points = data[5].inner_html

      player = Player.find_by(name: name, last_name: last_name)
      if player.nil?
        player = Player.create(name: name,	last_name: last_name, points: points)
        player.teams << team if !player.teams.include? team
      else
        player.update(name: name,	last_name: last_name,	points: points)
        player.teams << team if !player.teams.include? team
      end
      # update / create games
      url = "https://padel.cjimenez.org/#{player_info_url.split('=')[2]}.html"
      #url = "https://www.fmpadel.com/ligas_verEquiposDetV4.aspx?idCategoria=#{team.categoryID}&idJugador=#{player_info_url.split('=')[2]}"
      html = Nokogiri::HTML(URI.open(url))
      games_info = html.xpath('//div[@class="col-lg-6 card card-body"]/div')
      (games_info.count / 2).times do |t|
        data_game = games_info.shift.inner_html.split(': <b>')
        matchday = data_game[1].split('</b>')[0].to_i
        date = Date.parse(data_game[2].split('</b>')[0])
        if data_game[3].split('</b>')[0].eql? 'CLUB DEPORTIVO ELEMENTAL MIS PASITOS'
          homesite = true
        else
          homesite = false
        end
        players_info = games_info.shift.css('td')
        if homesite
          player1 = strip_tags(players_info[0].inner_html)
          player2 = strip_tags(players_info[4].inner_html)
        else
          player1 = strip_tags(players_info[3].inner_html)
          player2 = strip_tags(players_info[7].inner_html)
        end

        game = Game.find_by(season: team.season, team: team, matchday: matchday)
        if game.nil?
          game = Game.create(season: team.season, team: team, date: date, matchday: matchday, homesite: homesite, state: "close")
        else
          game.update(season: team.season, team: team, date: date, matchday: matchday, homesite: homesite)
        end

        [player1, player2].each do |p|
          player = Player.where("name || ' ' || last_name = ?", p).first
          games_player = GamesPlayer.find_by(game: game, player: player)
          if games_player.nil?
            GamesPlayer.create(game: game, player: player, played: true)
          else
            games_player.update(game: game, player: player, played: true)
          end
        end
      end
    end
    redirect_to team
  end

  # POST /teams or /teams.json
  def create
    @team = Team.new(team_params)

    url = "https://padel.cjimenez.org/#{@team.teamID}.html"
    #url = "https://www.fmpadel.com/ligas_verEquipos.aspx?idCategoria=#{@team.categoryID}&idEquipo=#{@team.teamID}"
    html = Nokogiri::HTML(URI.open(url))
    team_info = html.xpath('//div[@class="card card-body"]/div[@class="row"]/div[@class="col-xl-9"]/div[@class="row"]/div')
    @team.category = team_info[1].css('b').inner_html
    @team.group = team_info[2].css('b').inner_html
    @team.name = team_info[3].css('b').inner_html
    @team.short_name = team_info[3].css('b').inner_html

    temp_player = Player.new
    full_name = team_info[8].css('b').inner_html.split(" ")
    temp_player.name = full_name.shift
    temp_player.last_name = full_name.join(" ")
    temp_player.points = 0

    player = Player.find_by(name: temp_player.name, last_name: temp_player.last_name)
    if player.nil?
      # Creamos un jugador que hará las veces de capitan.
      temp_player.save
      @team.captainID = temp_player.id
      #temp_player.teams << @team
    else
      # Actualizamos al jugador que hará las veces de capitan.
      @team.captainID = player.id
      #player.teams << @team if !player.teams.include? @team
    end

    respond_to do |format|
      if @team.save
        format.html { redirect_to team_url(@team), notice: "Team was successfully created and captain was successfully created/updated." }
        format.json { render :show, status: :created, location: @team }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @team.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /teams/1 or /teams/1.json
  def update
    respond_to do |format|
      if @team.update(team_params)
        format.html { redirect_to team_url(@team), notice: "Team was successfully updated." }
        format.json { render :show, status: :ok, location: @team }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @team.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /teams/1 or /teams/1.json
  def destroy
    @team.destroy_with_players

    respond_to do |format|
      format.html { redirect_to teams_url, notice: "Team was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_team
    @team = Team.find(params[:id])
  end

  # Only allow a list of trusted parameters through.
  def team_params
    params.require(:team).permit(:name, :season_id, :category, :group, :categoryID, :teamID, :captainID)
  end
end
