about summary refs log tree commit diff stats
path: root/app/controllers/pokeviewer/pokemon_controller.rb
blob: 2c38e564825f5e2354c72b2117566873900da509 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
require_dependency "pokeviewer/application_controller"

module Pokeviewer
  class PokemonController < ApplicationController
    before_action :load_pokemon, only: [:show, :embed]

    def index
      pokemon = Pokemon.order("trainer_id IS NULL DESC").
        order(trainer_id: :asc).
        order(box: :asc).
        order(slot: :asc).
        joins(:current).
        includes(:current).
        chunk do |p|
          if p.trainer_id.nil?
            -1
          else
            p.trainer_id
          end
        end

      @unaccounted = []

      begin
        if pokemon.peek.first == -1
          @unaccounted = pokemon.next.second
        end
      rescue StopIteration
        # There are no Pokémon, but that's fine.
      end

      @trainers = Trainer.order(id: :asc).all.map do |trainer|
        if trainer.id == pokemon.peek.first
          party = []

          boxes = (1..14).map do |i|
            {
              name: trainer.box_name(i),
              pokemon: [nil] * 30
            }
          end

          pokemon.next.second.chunk do |p|
            if p.box.nil?
              -1
            else
              p.box
            end
          end.each do |box, pokes|
            if box == -1
              party = pokes
            else
              boxes[box-1][:pokemon] = (0..29).map do |i|
                if not pokes.empty? and (pokes.first.slot == i)
                  pokes.shift
                else
                  nil
                end
              end
            end
          end

          [trainer, party, boxes]
        else
          nil
        end
      end.compact
    end

    def show
    end

    def show_revision
      @revision = Revision.
        where(
          sequential_id: params[:revision_id],
          pokeviewer_pokemon: { uuid: params[:id] }
        ).includes(
          :species, :item, :move_1, :move_2, :move_3, :move_4,
          pokemon: [:trainer, :location]
        ).first

      @pokemon = @revision.pokemon

      render :show
    end

    def embed
      render layout: false
    end

    protected
      def load_pokemon
        @pokemon = Pokemon.includes(
            current: [
              :species, :item, :move_1, :move_2, :move_3, :move_4,
              pokemon: [:trainer, :location]]
          ).find_by_uuid! params[:id]

        @revision = @pokemon.current
      end
  end
end