# -*- coding: utf-8 -*-
class WorkingDay < ActiveRecord::Base
  
  named_scope :for_month, lambda { |date| date.present? ? { :conditions => "month = DATE('#{date.to_date.beginning_of_month}')" }: { } }
  
  def type_of_day(day)
    if weekends.split(", ").include? day.to_s
      "Выходные"
    else
      "Будни"
    end
  end

  def ams_percent_for_day(day)
    if weekends.split(", ").include? day.to_s
      30
    else
      20
    end
  end


  def self.find_or_create_for_year(year)
    working_calendar = []
    1.upto(12) do |month|
      date = Date.strptime(month.to_s+"."+year.to_s, '%m.%Y')
      month_calendar = self.find_by_month(date)
      unless month_calendar
        range = date.beginning_of_month..date.end_of_month
        days = range.select { |d| (1..5).include?(d.wday) }.size
        weekends = range.select { |d| [6, 0].include?(d.wday)}.map{|i| i.day}

        case month
        when 1
          days -= 6
          weekends += [1, 2, 3, 4, 5, 6, 7, 8]
        when 2
          days -= 1
          weekends += [23]
        when 3
          days -= 1
          weekends += [8]
        when 6
          days -= 1
          weekends += [12]
        when  11
          days -= 1
          weekends += [4]
        when 5
          days -= 2   
          weekends += [1, 9]       
        end
        weekends = weekends.uniq.sort.join(", ")
        month_calendar = self.create(:month => date, :working_days => days, :weekends => weekends)
      end
      working_calendar << month_calendar
    end
    return working_calendar
  end

  def self.add_weekends
    for wd in self.all do
      date = wd.month
      range = date.beginning_of_month..date.end_of_month
      weekends = range.select { |d| [6, 0].include?(d.wday)}.map{|i| i.day}
      case date.month
      when 1
        weekends += [1, 2, 3, 4, 5, 6, 7, 8]
      when 2
        weekends += [23]
      when 3
        weekends += [8]
      when 5
        weekends += [1, 9]
      when 6
        weekends += [12]
      when 11         
        weekends += [4]
      end
      weekends = weekends.uniq.sort
      working_days = range.count - weekends.size  
      wd.update_attributes(:weekends => weekends.join(", "), :working_days => working_days)       
    end
  end

end
