require 'active_support/concern'

module EstoqueConcern extend ActiveSupport::Concern

  def atualiza_saldo_no_sub_estoque(estoque)
    quantidade = self.quantidade
    sub_estoque_destino = estoque.sub_estoques_por_validade.find_by( estoque_id: estoque )
    if sub_estoque_destino.nil?
      sub_estoque_destino = estoque.sub_estoques_por_validade.create(validade: Date.today, quantidade: 0)
      sub_estoque_destino.save!
    end

    while(quantidade > 0)
      sub_estoque_origem = self.estoque.sub_estoques_por_validade.where("quantidade > 0 ").order("validade ASC").first rescue nil
      break if sub_estoque_origem.nil?

      if quantidade >= sub_estoque_origem.quantidade
        sub_estoque_destino.quantidade += sub_estoque_origem.quantidade
        sub_estoque_destino.validade = sub_estoque_origem.validade
        sub_estoque_destino.save!
        quantidade = quantidade - sub_estoque_origem.quantidade
        sub_estoque_origem.update_attribute(:quantidade, 0)
      else
        sub_estoque_destino.quantidade += quantidade
        sub_estoque_destino.validade = sub_estoque_origem.validade
        sub_estoque_destino.save!
        sub_estoque_origem.update_attribute(:quantidade, sub_estoque_origem.quantidade - quantidade)
        break
      end

      if (sub_estoque_origem.quantidade.to_f < sub_estoque_destino.quantidade.to_f) && quantidade > 0
        sub_estoque_destino = estoque.sub_estoques_por_validade.create(validade: Date.today, quantidade: 0)
        sub_estoque_destino.save!
      end

    end
  end

  def estoque_do_mes_encerrado?(data = nil)
    return false unless data || session[:contexto_tipo] == 'Gestao_de_Estoque'
    GestaoDeEstoque::ControleDoAlmoxarifado.exists?(
      orcamento_id: (contexto_atual ? contexto_atual.id : orcamento_id),
      data_de_encerramento: data ? data.beginning_of_month..data.end_of_month : Date.today.beginning_of_month..Date.today.end_of_month
    )
  end

end
