require 'spec_helper'

describe IcecastMasterServerRelay do

  let(:relay) { IcecastMasterServerRelay.new }
  let(:output){ StringIO.new }
  let(:root)  { ::Builder::XmlMarkup.new(:target => output, :indent => 1) }


  it  "should not save" do
    relay.save.should be_false
    relay.errors[:master_pass].should == ["can't be blank", "is too short (minimum is 5 characters)"]
    relay.errors[:master_username].should == ["can't be blank", "is too short (minimum is 5 characters)"]
    relay.errors[:master_server].should == ["is too short (minimum is 1 character)"]
  end

  it "should save" do
    relay.master_server = "test.www.com"
    relay.master_server_port = 7111
    relay.master_username = "hackme-user"
    relay.master_pass = "hackme-password"
    relay.save!

    root.tag! 'root' do |builder|
      relay.dumpXml(builder)
    end

    output.rewind
    xml = Nokogiri::XML(output)
    xml.css('root master-server').text.should == relay.master_server.to_s
    xml.css('root master-server-port').text.should == relay.master_server_port.to_s
    xml.css('root master-update-interval').text.should == relay.master_update_interval.to_s
    xml.css('root master-username').text.should == relay.master_username.to_s
    xml.css('root master-password').text.should == relay.master_pass.to_s
    xml.css('root relays-on-demand').text.should == relay.relays_on_demand.to_s
  end

  describe "poke configs" do
    let(:server) { a = FactoryGirl.create(:icecast_server_with_overrides); a.config_updated; IcecastServer.find(a.id) }

    before(:each) do
      server.master_relay = FactoryGirl.create(:icecast_master_server_relay)
      server.template.master_relay = FactoryGirl.create(:icecast_master_server_relay)
      server.template.save!
      server.save!
      server.config_updated
      server.reload
    end

    it "success via template" do
      server.template.master_relay.save!
      server.reload
      server.config_changed.should == 1
    end

    it "delete via template" do
      server.template.master_relay.destroy
      server.reload
      server.config_changed.should == 1
    end

    it "success via server" do
      server.master_relay.save!
      server.reload
      server.config_changed.should == 1
    end

    it "delete via server" do
      server.master_relay.destroy
      server.reload
      server.config_changed.should == 1
    end
  end

end