module Bits
  class ActualsController < Bits::BaseController

    def index
      authorize Actual

      @platforms = Actual.platforms
      @actuals = []

      unless params[:month_year].present?
        params[:month_year] = Time.new.strftime("%m-%Y")
      end

      unless params[:platform].present?
        params[:platform] = Actual.platforms[0]
      end

      unless Actual.platforms.include?(params[:platform])
        flash[:error] = "Invalid platform"
        return
      end

      begin
        month_year_time = Date.strptime(params[:month_year], '%m-%Y')
      rescue ArgumentError
        flash[:error] = "Invalid month"
        return
      end

      params[:month_year] = month_year_time.strftime("%m-%Y")

      begin
        @actuals = Actual.all(month_year_time.month, month_year_time.year, params[:platform])
      rescue StandardError
        flash[:error] = "Error retrieving actuals"
      end
    end

    def configure_actuals
      authorize Actual

      unless params[:actuals].present?
        flash[:error] = "Actuals are required"
        return redirect_back
      end

      actuals_to_update = params.require(:actuals).permit!.to_h.transform_values(&:to_i)

      unless params[:month_year].present?
        flash[:error] = "Month is required"
        return redirect_back
      end

      begin
        month_year_time = Date.strptime(params[:month_year], '%m-%Y')
      rescue ArgumentError
        flash[:error] = "Invalid month"
        return redirect_back
      end

      unless params[:platform].present?
        flash[:error] = "Platform is required"
        return redirect_back
      end

      begin
        Actual.configure(month_year_time.month, month_year_time.year, params[:platform], actuals_to_update)
      rescue StandardError
        flash[:error] = "Error updating actuals"
        return redirect_back
      end

      flash[:success] = "Successfully updated actuals"
      redirect_back
    end

  end
end