module Promotions
  class BackfillChannelsController < Promotions::BaseController
    before_action :set_backfill_channel, only: [:show, :edit, :update, :destroy]

    def index
      authorize BackfillChannel
      #sort by active channels and latest updated
      @backfill_channels = Promotions::BackfillChannel.all.sort_by { |channel| channel.active.to_s + ' ' + channel.updated_at.to_i.to_s }.reverse
    end

    def show
      @audits = History::QueryAudit.all(PromotionAudit.promotion_audit_params('backfill_channel', @backfill_channel))
    end

    def new
      @backfill_channel = BackfillChannel.new
      @backfill_channel.reporter = current_user.ldap_login
      authorize @backfill_channel
    end

    def create
      @backfill_channel = BackfillChannel.new backfill_channel_params
      @backfill_channel.reporter = current_user.ldap_login
      authorize @backfill_channel
      if @backfill_channel.save
        flash[:success] = "Success"
        History::AddAudit.add(PromotionAudit.new_audit('backfill_channel', @backfill_channel))
        redirect_to promotions_backfill_channel_path(@backfill_channel)
      else
        flash.now[:danger] = @backfill_channel.errors.full_messages.to_sentence
        render :new
      end
    end

    def edit
    end

    def update
      if @backfill_channel.update(backfill_channel_params)
        flash[:success] = "Success"
        History::AddAudit.add(PromotionAudit.update_audit('backfill_channel', @backfill_channel))
        redirect_to promotions_backfill_channel_path(@backfill_channel)
      else
        flash.now[:danger] = @backfill_channel.errors.full_messages.to_sentence
        render :edit
      end
    end

    def destroy
      if @backfill_channel.destroy
        History::AddAudit.add(PromotionAudit.delete_audit('backfill_channel', @backfill_channel))
        flash[:success] = "Success"
      else
        flash[:error] = @backfill_channel.errors.full_messages.to_sentence
      end

      redirect_back
    end

    protected

    def set_backfill_channel
      id = params[:id]
      @backfill_channel = BackfillChannel.find id
      unless @backfill_channel.errors.empty?
        flash[:error] = @backfill_channel.errors.full_messages.to_sentence
        return redirect_to promotions_backfill_channels_path
      end
      authorize @backfill_channel
      @backfill_channel.reporter = current_user.ldap_login
    end

    def backfill_channel_params
      params.require(:promotions_backfill_channel).permit(:id, :user_id, :login, :priority, :title, :description_raw, :image_url, :language, :active, :sponsored)
    end
  end
end
