1require_dependency 'archived'
 
2
 
3module Archived
 
4  class DebateOutcome < ActiveRecord::Base
 
5    # By default we want the user to upload a '2x' style image, and we can then
 
6    # resize it down with Imagemagick
 
7    COMMONS_IMAGE_SIZE = { w: 1260.0, h: 710.0 }
 
8
 
 9    belongs_to :petition, touch: true
 
 
11    validates :petition, presence: true
 
12    validates :debated_on, presence: true, if: :debated?
 
13    validates :transcript_url, :video_url, :debate_pack_url, length: { maximum: 500 }
 
 
15    has_attached_file :commons_image,
 
16      # default_url needs to be a lambda - this way the generated image url will
 
17      # include any asset-digest
 
18      default_url: ->(_) { ActionController::Base.helpers.image_url("graphics/graphic_house-of-commons.jpg") },
 
19      styles: {
 
20        "1x": "#{(COMMONS_IMAGE_SIZE[:w]/2).to_i}x#{(COMMONS_IMAGE_SIZE[:h]/2).to_i}",
 
21        "2x": "#{COMMONS_IMAGE_SIZE[:w]}x#{COMMONS_IMAGE_SIZE[:h]}"
 
22      }
 
 
24    validates_attachment_content_type :commons_image, content_type: /\Aimage\/.*\Z/
 
25    validate :validate_commons_image_dimensions, unless: :no_commons_image_queued
 
 
27    after_create do
 
28      petition.touch(:debate_outcome_at) unless petition.debate_outcome_at?
 
29    end
 
 
31    after_save do
 
32      petition.update_columns(debate_state: debate_state)
 
33    end
 
 
35    def date
 
36      debated_on
 
37    end
 
 
39    private
 
 
41    def debate_state
 
42      debated? ? 'debated' : 'not_debated'
 
43    end
 
 
45    def image_ratio(width, height)
 
46      (width.to_f / height.to_f).round(2)
 
47    end
 
 
49    def no_commons_image_queued
 
50      commons_image.blank? || !commons_image.queued_for_write[:original]
 
51    end
 
 
53    def validate_commons_image_dimensions
 
54      # This should be tuned if the images start looking badly scaled
 
55      max_ratio_delta = 0.1
 
 
57      dimensions = Paperclip::Geometry.from_file(commons_image.queued_for_write[:original].path)
 
 
59      if dimensions.width < COMMONS_IMAGE_SIZE[:w]
 
60        errors.add(:commons_image, :too_narrow, width: dimensions.width, min_width: COMMONS_IMAGE_SIZE[:w])
 
61      end
 
 
63      if dimensions.height < COMMONS_IMAGE_SIZE[:h]
 
64        errors.add(:commons_image, :too_short, height: dimensions.height, min_height: COMMONS_IMAGE_SIZE[:h])
 
65      end
 
 
67      expected_ratio = image_ratio(COMMONS_IMAGE_SIZE[:w], COMMONS_IMAGE_SIZE[:h])
 
68      actual_ratio = image_ratio(dimensions.width, dimensions.height)
 
 
70      min_ratio = (expected_ratio - max_ratio_delta).round(2)
 
71      max_ratio = (expected_ratio + max_ratio_delta).round(2)
 
72      unless (min_ratio..max_ratio).include? actual_ratio
 
73        errors.add(:commons_image, :incorrect_ratio, ratio: actual_ratio, min_ratio: min_ratio, max_ratio: max_ratio)
 
74      end
 
75    end
 
76  end
 
77end