module Habitable
  class HabitTimeValidator < ActiveModel::Validator
    def validate(record)
      # numbers, ie 135, only on days 1 3 5. Numbers from 1 - 7
      if record.habit_time =~ /^\d+/
        i = 0
        record.habit_time.each_char do |c|
          c = c.to_i
          if (c <= i)
            record.errors[:habit_time] << "invalid format"
          else
            if c > 7
              record.errors[:habit_time] << "invalid format"
            else
              i = c
            end
          end
        end
      # Everyday. If E + numbers, Everyday but on specific days.
      elsif record.habit_time =~ /^E/
        rest = record.habit_time[1..-1]
        i = 0
        rest.each_char do |c|
          c = c.to_i
          if (c <= i)
            record.errors[:habit_time] << "invalid format"
          else
            if c > 7
              record.errors[:habit_time] << "invalid format"
            else
              i = c
            end
          end
        end
      # W + 1 number, everyweek on specific day
      elsif record.habit_time =~ /^W/
        if record.habit_time.length == 2
          if record.habit_time[1].to_i > 7
            record.errors[:habit_time] << "invalid format"
          end
        else
          record.errors[:habit_time] << "invalid format"
        end

      elsif record.habit_time =~ /^M/

      else
        record.errors[:habit_time] << "invalid format"
      end
    end
  end
end
