ActiveAdmin.register_page "SchoolUserUploads" do

  menu :label => 'School User Upload', :parent => 'Misc'

  page_action :upload_schooluseruploads, :method => :post do
    User.transaction do

      puts params

      @client = RecurlyClient.new

      file = params[:jam_ruby_user][:csv]

      created = 0
      errors = 0
      updated = 0
      skipped = 0
      array_of_arrays = CSV.read(file.tempfile.path, headers: true, encoding: 'bom|utf-8')
      array_of_arrays.each do |row|
        school_name = row['School Name'].strip
        school_tag = row['School ID'].strip
        school = School.autocreate_find_from_upload(school_name, school_tag)
        first_name = row['First Name'].strip
        last_name = row['Last Name'].strip
        email_address = row['Email Address'].strip.downcase
        license_start = parse_date(row['License Start Date'].strip)
        license_end = parse_date(row['License End Date'].strip)
        source = row['Source'].strip
        password = SecureRandom.uuid
        options = {
            first_name: first_name,
            last_name: last_name,
            email: email_address,
            license_start: license_start,
            license_end: license_end,
            import_source: source,
            school_id: school.id,
            terms_of_service: true,
            musician: true,
            skip_recaptcha: true,
            password: password,
            password_confirmation: password
        }

        parse_user_type(row['User Type'].strip, options)

        instrument = Instrument.find('electric guitar')
        instruments= [{instrument_id: instrument.id, proficiency_level: 3, priority: 1}]
        options[:instruments] = instruments

        existing = User.find_by_email(options[:email])

        if existing
          if existing.import_source.nil?
            if options[:student]
              existing.school = school
              existing.is_a_student = true
              existing.import_source = options[:import_source]
              existing.license_start = options[:license_start]
              existing.license_end = options[:license_end]
            elsif options[:teacher]
              existing.school = school
              existing.import_source = options[:import_source]
              existing.license_start = options[:license_start]
              existing.license_end = options[:license_end]
              if existing.teacher.nil?
                existing.teacher = Teacher.build_teacher(existing, validate_introduction: true, biography: "Empty biography", school_id: school.id)
              end
            elsif options[:platform_instructor]
              existing.import_source = options[:import_source]
              existing.is_platform_instructor = true
              existing.license_start = options[:license_start]
              existing.license_end = options[:license_end]
            end

            existing.save

            if existing.errors.any?
              puts "User #{user.name} #{user.email} had errors"
              puts user.errors.inspect
              errors = errors + 1
            else
              @client.sync_subscription(existing)
              updated = updated + 1
              if options[:student]
                UserMailer.school_welcome_message(existing, nil).deliver_now
              elsif options[:teacher]
                UserMailer.school_welcome_message(existing, nil).deliver_now
              elsif options[:platform_instructor]

              end
            end
          else
            skipped = skipped + 1
          end
        else
          user = User.signup(options)

          if user.errors.any?
            puts "User #{user.name} #{user.email} had errors"
            puts user.errors.inspect
            errors = errors + 1
          else
            @client.sync_subscription(user)
            puts "User #{user.email} created"
            created = created + 1
          end
        end

      end

      redirect_to admin_schooluseruploads_path, :notice => "Created #{created}. Updated #{updated}. Errors #{errors}. Skipped #{skipped}"
    end
  end

  content do
    panel "Help" do
      link_to "Download Sample CSV", asset_path("Sample_School_User_Upload.csv", target: "_blank", download: "Sample_School_User_Upload.csv")
    end

    active_admin_form_for User.new, :url => admin_schooluseruploads_upload_schooluseruploads_path, :builder => ActiveAdmin::FormBuilder do |f|
      f.inputs "Upload School Users" do
        f.input :csv, as: :file, required: true, :label => "A school user upload"
      end
      f.actions
    end
  end
end

