require 'delayed_job'
class Request < ActiveRecord::Base

  attr_accessible :title, :description, :meta, :videos_attributes, :credentials_attributes, :timestamp_form

  belongs_to :user
  has_many :credentials, :dependent => :delete_all
  has_many :link_urls, :dependent => :delete_all
  has_many :videos, :dependent => :delete_all

  validates_associated :credentials, :length => {:minimum => 1}

  accepts_nested_attributes_for :credentials, :allow_destroy => true
  accepts_nested_attributes_for :link_urls, :allow_destroy => true
  accepts_nested_attributes_for :videos

  validates_presence_of :title, :description, :meta, :timestamp_form, :videos
  validates_length_of :meta, :minimum   => 3, :maximum   => 30, :tokenizer => lambda{ |value| value.split(',') }, :too_short => "must have at least %{count} keywords", :too_long  => "must have at most %{count} keywords"

  validates_uniqueness_of :timestamp_form

  def with_credentials_for(usr)
    SiteTemplate.active.compatible_with(usr).each do |st|
      credentials.build :name => st.name, :sitetemplate_id => st.id, :flag_sub => st.flag_sub, :flag => st.flag, :flag_cat => st.flag_cat
    end
    self
  end

  def with_linkurls_for(usr)
    SiteTemplate.active.compatible_with(usr).each do |st|
      link_urls.build :sitetemplate_id => st.id,  :name => st.name
    end
    self
  end

  def with_video_for(usr)
    videos.build :user_id => @user
    self
  end

  def upload(request)
    video = Video.find_by_request_id(request.id)
    request.credentials.checked.each do |link|
	puts link.pwd
	puts link.encrypted_pwd
        link.delay.distribute(link,request,video)
    end
  end

end