Move ICS match setup logic to a separate file.
[kaya.git] / lib / plugins / ics / lib / match_handler.rb
blobc11f7cc9946dc0251d8bed52f9294fa05c109ed6
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 require 'interaction/match'
9 require_bundle 'ics', 'icsplayer'
10 require_bundle 'ics', 'match_helper'
12 module ICS
15 # Handler for ICS games.
16
17 # Responds to ICS protocol events creating and updating matches.
18 # Matches are stored in the @matches instance variable. It is possible to
19 # have more than one match running on ICS because of the observe feature.
20
21 class MatchHandler
22   include Observer
23   
24   attr_reader :matches
25   
26   def initialize(user, protocol)
27     @protocol = protocol
28     @matches = { }
29     @user = user
30     
31     protocol.add_observer(self)
32   end
33   
34   def on_creating_game(data)
35     match = Match.new(data[:game], 
36         :kind => :ics,
37         :editable => false,
38         :time_running => true)
39     @matches[data[:number]] = [match, data.merge(:type => :played)]
40   end
41   
42   def on_end_game(data)
43     entry = @matches.delete(data[:game_number])
44     if entry
45       match, info = entry
46       match.close(data[:result], data[:message])
47     end
48   end
49   
50   def on_end_examination(number)
51     on_end_game(:game_number => number,
52                 :result => '',
53                 :message => '')
54   end
55   
56   def on_examination_revert(data)
57     match, match_info = @matches[data[:game_number]]
58     if match_info
59       match_info[:about_to_revert_to] = data[:index]
60     end
61   end
62   
63   def on_style12(style12)
64     # retrieve match and helper
65     match, match_info = @matches[style12.game_number]
66     helper = MatchHelper.create(style12)
67     if helper.nil?
68       warn "Unsupported style12. Skipping"
69       return
70     end
71     
72     # update match using helper and save it back to the @matches array
73     match = helper.get_match(@protocol, match, match_info, style12)
74     @matches[style12.game_number] = [match, match_info]
75     
76     if match.nil?
77       return
78     elsif match.started?
79       match_info[:icsplayer].on_style12(style12)
80     else
81       helper.start(@protocol, @user, match, match_info, style12)
82     end
83   end
84 end
86 end