# -*- encoding : utf-8 -*-
class TableRow < ApplicationRecord
  has_many :cel_tables, -> {order :position}
  belongs_to :table_content
  
  attr_accessor :skip_before_update




  before_create do
    if !position
      self.position = 1
    end
    if position
      TableRow.where(["position >= ? and table_content_id = ?",self.position,self.table_content_id]).each do |table_row|
        table_row.position = table_row.position + 1
        table_row.skip_before_update = true
        table_row.save!
      end
    end
  end

  before_update do
    if !skip_before_update
      if self.position_changed?
        #si la position est plus grande que l'ancienne
        if self.changes['position'][1] > self.changes['position'][0]
          TableRow.where(["position > ? and position <= ? and table_content_id = ?",self.changes['position'][0],self.changes['position'][1],self.table_content_id]).each do |table_row|
            table_row.position = table_row.position - 1
            table_row.skip_before_update = true
            table_row.save!
          end
        end
        #si la position est plus petite que l'ancienne.  
        if self.changes['position'][1] < self.changes['position'][0]
          TableRow.where(["position >= ? and position < ? and table_content_id = ?",self.changes['position'][1],self.changes['position'][0],self.table_content_id]).each do |table_row|
            table_row.position = table_row.position + 1
            table_row.skip_before_update = true
            table_row.save!
          end  
        end 
      end
    end
  end

  before_destroy do
    TableRow.where(["position > ? and table_content_id = ?",self.position,self.table_content_id]).each do |table_row|
      table_row.position = table_row.position - 1
      table_row.skip_before_update = true
      table_row.save!
    end
    
    table = self.table_content
    table_past_count = table.nbr_rows
    table.nbr_rows = table_past_count - 1
    table.save

  end
  
  
  def dup
    @new = TableRow.new(self.attributes)
    @new.id = nil
    @new.table_content_id = nil
    @new.save
    
    @new.cel_tables.destroy_all
    self.cel_tables.each do |cel_table|
      
      new_td = cel_table.dup
      new_td.table_row = @new
      new_td.save
      
    end
    
    @new
    
  end


end
