require 'rails_helper'

describe OwnerInitialization do
  describe "#window_from DayTimeMinutes" do

    it "works with assignment" do
      described_class.connection.execute "INSERT INTO #{described_class.table_name} (state, window_from, window_to, created_at, updated_at) VALUES ('pending', 78, 11656, TIME(), TIME())"
      record = described_class.first
      record.window_from.should eq DayTimeMinutes.new('01:18')
      record.window_from.should eq '01:18'
      record.window_from.should eq 78

      record.window_from = "16:48"
      record.window_from.should eq DayTimeMinutes.new('16:48')
      record.window_from.should eq '16:48'
      record.window_from.should eq 1008

      record.save
      record.errors.should be_empty

      described_class.connection.exec_query("SELECT window_from FROM #{described_class.table_name}").rows.should eq [[1008]]

      record.reload
      record.window_from.should eq '16:48'

      record = described_class.find(record.id)
      record.window_from.should eq '16:48'

      record.window_from = 789
      record.window_from.to_s.should eq '13:09'

      record.save
      record = described_class.find(record.id)
      record.window_from.to_s.should eq '13:09'

      record.update window_from: nil
      described_class.connection.exec_query("SELECT window_from FROM #{described_class.table_name}").rows.should eq [[nil]]

      # assign empty
      record.update window_from: ''
      record = described_class.find(record.id)
      record.window_from.should_not be_present
      record.window_from.number.should be nil
      record.window_from.should eq ''
    end

    it "works in queries" do
      record = create :owner_initialization, window_from: '13:56'
      column = described_class.arel_table[:window_from]
      described_class.where(column.gt record.window_from).select(:id).to_sql.should eq %|SELECT "owner_initializations"."id" FROM "owner_initializations" WHERE ("owner_initializations"."window_from" > 836)|
      described_class.where("window_from > ?", record.window_from).select(:id).to_sql.should eq %|SELECT "owner_initializations"."id" FROM "owner_initializations" WHERE (window_from > 836)|
    end

    it "works in queries with null value" do
      record = create :owner_initialization, window_from: nil
      column = described_class.arel_table[:window_from]
      described_class.where(column.gt record.window_from).select(:id).to_sql.should eq %|SELECT "owner_initializations"."id" FROM "owner_initializations" WHERE ("owner_initializations"."window_from" > NULL)|
      described_class.where("window_from > ?", record.window_from).select(:id).to_sql.should eq %|SELECT "owner_initializations"."id" FROM "owner_initializations" WHERE (window_from > NULL)|
    end
  end
end
