module Ads
  class SettingsController < ApplicationController
    before_action :set_setting, only: [:edit, :update]
    before_action :set_login, only: [:edit]

    def edit
    end

    def update
      @ad_setting.attributes = update_params
      if @ad_setting.save
        flash[:success] = "Success"
      else
        flash[:error] = "Error updating setting: #{@ad_setting.errors.messages[:base]}"
      end

      redirect_to twitch_user_path(params[:id])
    end

    def update_params
      {
        ad_server_default: params[:ad_server_default],
        force_client_ads: params[:force_client_ads],
        force_server_ads: params[:force_server_ads],
        guarantee_ads: params[:guarantee_ads],
        frequency: JSON.parse(params[:ad_break_settings])["frequency"],
        max_ad_break_length: JSON.parse(params[:ad_break_settings])["max_ad_break_length"],
        pbyp_disabled: params[:pbyp_disabled],
        required_age: params[:required_age],
        campaign_type: params[:campaign_type],
        turbo_disabled: params[:turbo_disabled],
        vod_ads_enabled: params[:vod_ads_enabled],
        vod_archive_midrolls: params[:vod_archive_midrolls],
        vod_archive_midrolls_frequency: JSON.parse(params[:vod_archive_midrolls_settings])["frequency"],
        vod_archive_midrolls_break_length: JSON.parse(params[:vod_archive_midrolls_settings])["break_length"],
        prerolls_disabled: params[:prerolls_disabled],
        postrolls_disabled: params[:postrolls_disabled],
      }
    end

    private

    def set_setting
      @ad_setting = Setting.find(params[:id])
      authorize @ad_setting
    end

    def set_login
      @user_login = Twitch::User.find(params[:id]).login
    end
  end
end
