# -*- coding: utf-8 -*-
## Шаблон рабочих смен
class RegularWorkShift < RegularShift
  has_many :work_shifts, :foreign_key => "regular_shift_id", :before_add => :set_attrs_for_shift


  def self.update_regulars(reg_was, new_shifts)
    reg_update = reg_was.select{|i| new_shifts.map{|c| c.employee_id}.include? i.employee_id}
    reg_destroy = reg_was.select{|i| !(new_shifts.map{|c| c.employee_id}.include? i.employee_id)}
    reg_new = new_shifts.select{|i| !(reg_was.map{|c| c.employee_id}.include? i.employee_id)}
    for r in reg_destroy do
      r.destroy
    end
    for r in reg_update do
      new_r = new_shifts.select{ |i| i.employee_id == r.employee_id}.first
      r.update_attributes(:time_from => new_r.time_from, :time_to => new_r.time_to) if new_r
    end
    for r in reg_new do
      rws = RegularWorkShift.create(:time_from => r.time_from, :time_to => r.time_to, :department => r.department, :employee_id => r.employee_id, :day_of_week => r.shift_date.strftime('%u'))
      r.update_attribute(:regular_shift_id, rws.id)
    end    
  end


  private
  def set_attrs_for_shift(shift)
    shift.employee_id = self.employee_id
    shift.time_from = time_from
    shift.time_to = time_to
    shift.department = department    
  end
end

