class PreTransfersController < ApplicationController
  before_action :set_pre_transfer, only: [:show, :edit, :update, :destroy]

  # GET /pre_transfers/new
  def new
    @pre_transfer = PreTransfer.new
  end

  # POST /pre_transfers
  # POST /pre_transfers.json
  def create
    @pre_transfer = PreTransfer.new(pre_transfer_params)
    @pre_transfer.user_id = current_user.id
    @pre_transfer.origin_is_pointsale = params[:pre_transfer][:origin_id].first == 'P' ? 1 : 0
    @pre_transfer.destiny_is_pointsale = params[:pre_transfer][:destiny_id].first == 'P' ? 1 : 0
    @pre_transfer.origin_id = params[:pre_transfer][:origin_id][2, params[:pre_transfer][:origin_id].length]
    @pre_transfer.destiny_id = params[:pre_transfer][:destiny_id][2, params[:pre_transfer][:destiny_id].length]
    respond_to do |format|
      if @pre_transfer.save
        if @pre_transfer.origin_is_pointsale == 1
          stock = AvailableProduct.find_by(:pointsale_id =>  @pre_transfer.origin_id,
            :product_id => @pre_transfer.product_id)
        else
          stock = WarehouseStock.find_by(:warehouse_id => @pre_transfer.origin_id,
            :product_id => @pre_transfer.product_id)
        end
        stock.stock = stock.stock -= @pre_transfer.quantity
        stock.save
        format.js
      else
        format.json { render json: @pre_transfer.errors.values, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /pre_transfers/1
  # PATCH/PUT /pre_transfers/1.json
  def update
    respond_to do |format|
      if @pre_transfer.origin_is_pointsale == 1
        stock = AvailableProduct.find_by(:pointsale_id =>  @pre_transfer.origin_id,
          :product_id => @pre_transfer.product_id)
      else
        stock = WarehouseStock.find_by(:warehouse_id => @pre_transfer.origin_id,
          :product_id => @pre_transfer.product_id)
      end
      #regresarle al stock la cantidad a traspasar que estaba anteriormente
      stock.stock += @pre_transfer.quantity
      new_quantity = params[:pre_transfer][:quantity].to_i
      stock.stock = stock.stock -= new_quantity
      if stock.stock >= 0
        if @pre_transfer.update(pre_transfer_params)
          stock.save
          format.json { head :ok }
        else
          format.json { render json: @pre_transfer.errors, status: :unprocessable_entity }
        end
      else
        @pre_transfer.errors.add(:product, "El stock actual del producto es insuficiente.")
        format.json { render json: @pre_transfer.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /pre_transfers/1
  # DELETE /pre_transfers/1.json
  def destroy
    respond_to do |format|
      if @pre_transfer.origin_is_pointsale == 1
        stock = AvailableProduct.find_by(:pointsale_id =>  @pre_transfer.origin_id,
          :product_id => @pre_transfer.product_id)
      else
        stock = WarehouseStock.find_by(:warehouse_id => @pre_transfer.origin_id,
          :product_id => @pre_transfer.product_id)
      end
      if @pre_transfer.destroy
        stock.stock += @pre_transfer.quantity
        stock.save
        format.json { head :ok }
      end
    end
  end

  def add_pre_transfer_by_barcode
    respond_to do |format|
      @pre_transfer = PreTransfer.new
      @pre_transfer.user_id = current_user.id

      #dependiendo del prefijo que traiga W o P determinar de que tipo es el origen.
      @pre_transfer.origin_is_pointsale = params[:origin_id].first == 'P' ? 1 : 0
      @pre_transfer.destiny_is_pointsale = params[:destiny_id].first == 'P' ? 1 : 0
      @pre_transfer.origin_id = params[:origin_id][2, params[:origin_id].length]
      @pre_transfer.destiny_id = params[:destiny_id][2, params[:destiny_id].length]

      if @pre_transfer.origin_is_pointsale == 1
        origin = Pointsale.find(@pre_transfer.origin_id)
        product = origin.products.find_by("barcode = ? and stock > 0", params[:barcode])
      else
        origin = Warehouse.find(@pre_transfer.origin_id)
        product = origin.products.find_by("barcode = ? and stock > 0", params[:barcode])
      end

      if product.blank?
        @error = "No existe producto escaneado o no tiene stock"
      else
        @pre_transfer.product_id = product.id
        @pre_transfer.quantity = 1
        if @pre_transfer.save

          if @pre_transfer.origin_is_pointsale == 1
            stock = AvailableProduct.find_by(:pointsale_id =>  @pre_transfer.origin_id,
              :product_id => product.id)
          else
            stock = WarehouseStock.find_by(:warehouse_id => @pre_transfer.origin_id,
            :product_id => product.id)
          end

          stock.stock = stock.stock -= @pre_transfer.quantity
          stock.save
        end
      end
      format.js { render :action => "create" }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_pre_transfer
      @pre_transfer = PreTransfer.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def pre_transfer_params
      params.require(:pre_transfer).permit(:origin_id, :destiny_id, :user_id, :product_id, :quantity)
    end
end
