ActiveAdmin.register JamRuby::User, :as => 'Users' do

  searchable_select_options(scope: User.all,
                            text_attribute: :username,
                            filter: lambda do |term, scope|
                              scope.ransack(full_name_or_email_cont: term).result
                            end)

  collection_action :autocomplete_user_email, :method => :get

  actions :all, :except => [:destroy]

  menu :label => 'Users', :parent => 'Users'

  config.sort_order = 'created_at DESC'

  filter :jamuser_full_name_or_email_cont, label: 'Name Or Email', as: :string
  filter :created_at
  filter :updated_at
  filter :import_source

  includes :purchased_jam_tracks, :jam_track_rights => :jam_track, :taken_lessons => :music_session, :taught_lessons => :music_session

  form :partial => "form"

  member_action :delete_forever, :method => :get do
    resource.permanently_delete
    redirect_to :back, {notice: 'User email and login credentials have been permanently changed'}
  end


  #Notification.send_reload(connection.client_id)

  member_action :give_free_plan, :method => :get do
    @client = RecurlyClient.new
    plan_code = params[:plan_code]
    if params[:plan_code] == ''
      plan_code = nil
    end

    resource.update_admin_override_plan_code(plan_code)
    redirect_to :back, {notice: "User got a free plan via adminstrative override to #{params[:plan_code]}"}
  end

  member_action :revoke_free_plan, :method => :get do
    resource.update_admin_override_plan_code(nil)
    redirect_to :back, {notice: "User has administrative free plan removed"}
  end


  member_action :resend_welcome_email, :method => :get do
    user = resource
    if user.is_a_student
      if user.import_source
        reset_url = resource.create_tokened_reset_url
        UserMailer.school_welcome_message(user, reset_url).deliver_now
      else
        UserMailer.student_welcome_message(user).deliver_now
      end
    elsif user.is_a_teacher
      if user.import_source
        reset_url = resource.create_tokened_reset_url
        UserMailer.school_welcome_message(user, reset_url).deliver_now
      else
        UserMailer.teacher_welcome_message(user).deliver_now
      end
    elsif user.is_platform_instructor
      reset_url = resource.create_tokened_reset_url
      UserMailer.welcome_message(user, reset_url).deliver_now
    else
      UserMailer.welcome_message(user).deliver_now
    end

    redirect_to :back, {notice: "Resent Welcome Email"}
  end

  member_action :sync_subscription, :method => :get do
    @client = RecurlyClient.new
    @client.sync_subscription(resource)
    redirect_to :back, {notice: "Check the Subscription Plan Code, Subscription Sync Code, Subscription Sync Msg"}
  end

  member_action :reset_monthly_play, :method => :get do
    resource.used_month_play_time = 0
    resource.save!
    redirect_to :back, {notice: "Reset user's monthly play time to 0"}
  end

  member_action :change_to_plan, :method => :get do
    @client = RecurlyClient.new
    plan_code = params[:plan_code]
    if params[:plan_code] == ''
      plan_code = nil
    end

    result, subscription, account = @client.update_desired_subscription(resource, plan_code)
    redirect_to :back, {notice: "Set user's desired plan. "}
  end
  member_action :quick_reset, :method => :get do
    resetting_to = 'jellyandjam123'
    resource.change_password(resetting_to, resetting_to)
    resource.save
    redirect_to :back, {notice: "Reset password to #{resetting_to }"}
  end

  member_action :create_reset, :method => :get do
    reset_url = resource.create_tokened_reset_url
    redirect_to :back, {notice: "Reset password url created: #{reset_url}"}
  end

  member_action :end_trial, :method => :get do
    if Time.now - 2.days < resource.subscription_trial_ends_at
      resource.subscription_trial_ends_at = 3.days.ago
      resource.save!
      redirect_to :back, {notice: "User's trial ended"}
    else
      redirect_to :back, {notice: "Users trial already ended > 2 days ago.  Left alone user account"}
    end


  end



  show do |user|
    panel "Common" do
      attributes_table do
        row :id
        row :email
        row :admin
        row :updated_at
        row :created_at
        row :musician
        row :city
        row :state
        row :country
        row :first_name
        row :last_name
        row :birth_date
        row :gender
        row :email_confirmed
        row :remember_token
=begin
        row "Session Ready" do |user|
          div do
            if user.ready_for_session_at
              span do
                'YES'
              end
              span do
                br
              end
              span do
                link_to("mark as not checked", mark_session_not_ready_admin_student_path(user.id), {confirm: "Mark as not ready for session?"})
              end
            else
              span do
                'NO'
              end
              span do
                br
              end
              span do
                link_to("mark as checked", mark_session_ready_admin_student_path(user.id), {confirm: "Mark as ready for session?"})
              end

            end
          end
        end
=end
        row "Delete Forever" do |user|
          span do
            link_to("delete forever", delete_forever_admin_user_path(user.id),  :data => {:confirm => 'Are you sure?'})
          end
        end

        row "Quick Password Reset" do |user|
          span do
            link_to("reset password to jellyandjam123", quick_reset_admin_user_path(user.id),  :data => {:confirm => 'Reset password to jellyandjam123 ?'})
          end
        end

        row "Send Password Reset Email" do |user|
          span do
            Rails.application.config.external_root_url + "/request_reset_password"
          end
        end

        row "Password Reset URL" do |user|
          span do
            link_to("create reset URL", create_reset_admin_user_path(user.id),  :data => {:confirm => 'Are you sure?'})
          end
        end

        row "Resend Welcome Email" do |user|
          span do
            link_to("resend welcome email", resend_welcome_email_admin_user_path(user.id),  :data => {:confirm => 'Are you sure?'})
          end
        end

        row "Subscription" do |user|
          div do
            attributes_table do
              row :subscription_plan_code
              row :desired_plan_code
              row :admin_override_plan_code
              row :admin_override_ends_at
              row :recurly_subscription_state
              row :recurly_subscription_id
              row :desired_plan_code_set_at
              row :subscription_plan_code_set_at
              row :subscription_last_checked_at
              row :subscription_trial_ends_at
              row :subscription_sync_code
              row :subscription_sync_msg
              row :is_past_due
              row :stored_credit_card
              row "Monthly Time Used" do |user|
                div do
                  remaining_month_play_time = user.subscription_rules[:remaining_month_play_time]
                  if remaining_month_play_time.nil?
                    span do
                      "No limit"
                    end
                  elsif user.played_this_month?
                    span do
                      "Used: #{user.used_month_play_time / 60} min | Remaining #{remaining_month_play_time / 60} min"
                    end
                  else
                    span do
                      "Did not play this month. Last played #{user.used_current_month}"
                    end
                  end
                end
              end
            end
          end
          div do
            'DESIRED PLAN CODE = What plan the user has selected in the UI'
          end
          div do
            'SUBSCRIPTION PLAN CODE = What plan the user actually has'
          end
          div do
            div do
              user.recurly_code ? link_to('Recurly Account', user.recurly_link_to_account, target: "_blank", ) : span do 'No Recurly Account' end
            end
            div do
              user.recurly_subscription_id ? link_to('Recurly Subscription', user.recurly_link_to_subscription, target: "_blank", ) : span do 'No Recurly Subscription' end
            end
          end
          div do
            h3 do
              'Give Free Plan Actions'
            end
            h4 do
              'sets secret override to give user a free plan (link goes to another page)'
            end
            div do
              link_to("give no-payment plan", edit_admin_user_override_path(user.id))
            end
          end
          div do
            h3 do
              'Reset Monthly Play Time'
            end
            h4 do
              'sets the user\'s monthly play time to 0'
            end
            div do
              link_to("reset monthly play time", reset_monthly_play_admin_user_path(user.id),  :data => {:confirm => 'Are you sure?'})
            end
          end
          div do
            h3 do
            'Change Plan Actions'
            end
            h4 do
              'Change desired plan exactly as if the user did it on /client#/accounts/subscription'
            end
            div do
              link_to("change plan to silver monthly", change_to_plan_admin_user_path(user.id, plan_code: 'jamsubsilver'),  :data => {:confirm => 'Are you sure?'})
            end
            div do
              link_to("change plan to gold monthly", change_to_plan_admin_user_path(user.id, plan_code: 'jamsubgold'),  :data => {:confirm => 'Are you sure?'})
            end
            div do
              link_to("change plan to platinum monthly", change_to_plan_admin_user_path(user.id, plan_code: 'jamsubplatinum'),  :data => {:confirm => 'Are you sure?'})
            end
            div do
              link_to("change plan to silver yearly", change_to_plan_admin_user_path(user.id, plan_code: 'jamsubsilveryearly'),  :data => {:confirm => 'Are you sure?'})
            end
            div do
              link_to("change plan to gold yearly", change_to_plan_admin_user_path(user.id, plan_code: 'jamsubgoldyearly'),  :data => {:confirm => 'Are you sure?'})
            end
            div do
              link_to("change plan to platinum yearly", change_to_plan_admin_user_path(user.id, plan_code: 'jamsubplatinumyearly'),  :data => {:confirm => 'Are you sure?'})
            end
            div do
              link_to("change plan to free", change_to_plan_admin_user_path(user.id, plan_code: ''),  :data => {:confirm => 'Are you sure?'})
            end

          end
          div do
            h3 do
              'Force Sync'
            end
            h4 do
              'exactly same as background job that checks accounts'
            end
            div do
              link_to("force sync", sync_subscription_admin_user_path(user.id),  :data => {:confirm => 'Are you sure?'})
            end
          end

          div do
            h3 do
              'End Trial'
            end
            h4 do
              'ends the trial as of 3 days ago'
            end
            div do
              link_to("end trial", end_trial_admin_user_path(user.id),  :data => {:confirm => 'Are you sure?'})
            end
          end
        end


        row :jamclass_credits
        row :via_amazon
        row "Web Profile" do
          link_to "Link", "#{Rails.application.config.external_root_url}/client#/profile/#{user.id}"
        end
        row :image do
          user.photo_url ? image_tag(user.photo_url) : ''
        end
        row "Instruments" do
          table_for user.musician_instruments.order('proficiency_level desc') do
            column :instrument_id
          end

        end
      end

    end
    panel "Onboarding" do
      attributes_table do
        row :onboarding_status
        row "Support Consultant" do |user|
          if user.onboarder
            link_to "#{user.onboarder.name} (#{user.onboarder.onboarding_users.count})", user.onboarder.admin_url
          else
          end
        end
        row "Signup" do
          user.created_at.to_date
        end
        row "Assigned", :onboarder_assigned_at
        row "Email 1", :onboarding_email_1_sent_at
        row "Email 2", :onboarding_email_2_sent_at
        row "Email 3", :onboarding_email_3_sent_at
        row "Email 4", :onboarding_email_4_sent_at
        row "Email 5", :onboarding_email_5_sent_at
        row "Test Session Scheduled Time", :onboarding_test_session_at
        row "When Test Session Was Requested", :onboarding_test_session_at
        row "Test Session Outcome", :onboarding_test_session_outcome
        row "Notes", :onboarding_onboarder_notes
        row "Lost Reason", :onboarding_lost_reason
        row "Lost At", :onboarding_lost_at
        row "Escalated Reason", :onboarding_escalation_reason
        row "Escalated At", :onboarding_escalated_at

      end
    end
=begin

    panel "Teacher Setting" do
      attributes_table do
        row :is_searchable
      end
    end if user.teacher


    panel "Lessons" do
      attributes_table do
        row "Taken Lessons" do
          table_for user.taken_lessons.order('created_at desc') do
            column "View" do |lesson_session|
              link_to("View", lesson_session.admin_url)
            end
            column :created_at
            column :status
            column "Teacher" do |lesson_session|
              teacher = lesson_session.teacher
              span do
                link_to teacher.admin_name, teacher.admin_url
              end
            end
            column "Start Time" do |lesson_session|
              span do
                lesson_session.music_session.pretty_scheduled_start(true)
              end
              br
              span do
                lesson_session.music_session.scheduled_start
              end
            end

          end
        end
        row "Taught Lessons" do
          table_for user.taught_lessons.order('created_at desc') do
            column "View" do |lesson_session|
              link_to("View", lesson_session.admin_url)
            end
            column :created_at
            column :status
            column "Student" do |lesson_session|
              student = lesson_session.student
              span do
                link_to student.admin_name, student.admin_name
              end
            end
            column "Start Time" do |lesson_session|
              span do
                lesson_session.music_session.pretty_scheduled_start(true)
              end
              br
              span do
                lesson_session.music_session.scheduled_start
              end
            end

          end
        end

      end


    end
=end

    panel "JamTracks" do
      div do
        link_to "Give JamTrack", "../jam_track_rights/new"
      end

      attributes_table do
        row "Purchased JamTracks" do
          table_for user.purchased_jam_tracks.unscope(:order).order('original_artist asc', 'name asc') do
            column "Artist", :original_artist
            column "Name", :name
            column "Can Download", :can_download
            column "Version", :version
            column "ID", :id
          end
        end
      end
    end

    active_admin_comments
  end

  index do
    # actions # use this for all view/edit/delete links
    column "Actions" do |user|
      links = ''.html_safe
      links << link_to("View", resource_path(user), :class => "member_link view_link")
      links << link_to("Edit", edit_resource_path(user), :class => "member_link edit_link")
      links
    end

    column "Email" do |user|
      link_to user.email, resource_path(user)
    end
    column :subscription_plan_code
    column :desired_plan_code
    column :created_at
    column :first_name
    column :last_name
    column :city
    column :state
  end

  controller do

    # this actually searches on first name, last name, and email, because of get_autocomplete_items defined below
    autocomplete :user, :email, :full => true, :display_value => :autocomplete_display_name

    def get_autocomplete_items(parameters)
      User.select("email, first_name, last_name, id").where(["email ILIKE ? OR first_name ILIKE ? OR last_name ILIKE ?", "%#{parameters[:term]}%", "%#{parameters[:term]}%", "%#{parameters[:term]}%"])
    end


    def create
      @jam_ruby_user = JamRuby::User.new(params[:jam_ruby_user])
      @jam_ruby_user.administratively_created = true
      if @jam_ruby_user.password.nil? || @jam_ruby_user.password.length == 0
        # a nil password in the form  means we simply won't create one; however,
        # the password_digest has to be set to something to make 'has_secure_password' happy
        @jam_ruby_user.password_digest = SecureRandom.urlsafe_base64
      end

      # call `create!` to ensure that the rest of the action continues as normal
      create!
    end

    def update

      @user = resource
      @user.email = params[:jam_ruby_user][:email]
      @user.admin = params[:jam_ruby_user][:admin]
      @user.is_onboarder = params[:jam_ruby_user][:is_onboarder]
      @user.subscribe_email = params[:jam_ruby_user][:subscribe_email]
      @user.musician = params[:jam_ruby_user][:musician]
      @user.first_name = params[:jam_ruby_user][:first_name]
      @user.last_name = params[:jam_ruby_user][:last_name]
      @user.state = params[:jam_ruby_user][:state]
      @user.city = params[:jam_ruby_user][:city]
      @user.is_platform_instructor = params[:jam_ruby_user][:is_platform_instructor]
      @user.gifted_jamtracks = params[:jam_ruby_user][:gifted_jamtracks]


      if params[:jam_ruby_user][:show_frame_options].to_i == 1
        @user.mod_merge({User::MOD_GEAR => {User::MOD_GEAR_FRAME_OPTIONS => true}})
      else
        @user.delete_mod(User::MOD_GEAR, User::MOD_GEAR_FRAME_OPTIONS)
      end


      if params[:jam_ruby_user][:how_to_use_video_no_show].to_i == 1
        @user.mod_merge({User::MOD_NO_SHOW => {User::HOWTO_USE_VIDEO_NOSHOW => true}})
      else
        @user.delete_mod(User::MOD_NO_SHOW, User::HOWTO_USE_VIDEO_NOSHOW)
      end


      if params[:jam_ruby_user][:configure_video_no_show].to_i == 1
        @user.mod_merge({User::MOD_NO_SHOW => {User::CONFIGURE_VIDEO_NOSHOW => true}})
      else
        @user.delete_mod(User::MOD_NO_SHOW, User::CONFIGURE_VIDEO_NOSHOW)
      end


      @user.save!

      redirect_to edit_admin_user_path(@user)

    end
  end

end