module Promotions
  class ScheduledVodsController < Promotions::BaseController
    before_action :set_scheduled_vod, only: [:show, :edit, :update, :destroy, :clone]

    def index
      authorize ScheduledVod
      #sort by earliest start date of scheduled vod
      @scheduled_vods = Promotions::ScheduledVod.all.sort_by { |vod| vod.start_date.to_s }.reverse
    end

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

    def new
      if id = params[:duplicate]
        source = ScheduledVod.find id

        @scheduled_vod = source.duplicate
      else
        @scheduled_vod = ScheduledVod.new
      end
      @scheduled_vod.reporter = current_user.ldap_login
      authorize @scheduled_vod
    end

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

    def edit
    end

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

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

      redirect_back
    end

    protected

    def set_scheduled_vod
      id = params[:id]
      @scheduled_vod = ScheduledVod.find id
      unless @scheduled_vod.errors.empty?
        flash[:error] = @scheduled_vod.errors.full_messages.to_sentence
        return redirect_to promotions_scheduled_vods_path
      end
      authorize @scheduled_vod
      @scheduled_vod.reporter = current_user.ldap_login
    end

    def scheduled_vod_params
      params.require(:promotions_scheduled_vod).permit(:id, :vod_id, :user_id, :login, :priority, :title, :description_raw, :image_url, :languages, :start_date, :start_date_part, :start_time_part, :end_date, :end_date_part, :end_time_part, :sponsored)
    end
  end
end
