# rubocop:disable Metrics/AbcSize
require 'fastlane/erb_template_helper'
require 'ostruct'
require 'rexml/document'
require 'aws-sdk'

module Fastlane
  module Actions

    Upload_S3_File_ARGS_MAP = {
      file: '-f',
      access_key: '-a',
      secret_access_key: '-s',
      bucket: '-b',
      region: '-r',
      acl: '--acl',
      path: '-P',
      s3_file_name: '-n'
    }

  class UploadS3FileAction < Action
      def self.run(config)
        # Calling fetch on config so that default values will be used
        params = {}
        params[:file] = config[:file]
        params[:bucket] = config[:bucket]
        params[:acl] = config[:acl]
        params[:path] = config[:path]
        params[:s3_file_name] = config[:s3_file_name]

        # Pulling parameters for other uses
        s3_subdomain = params[:region] ? "s3-#{params[:region]}" : "s3"
        s3_bucket = params[:bucket]
        file = params[:file]
        s3_path = params[:path]
        s3_file_name = params[:s3_file_name]        

        raise "No S3 bucket given, pass using `bucket: 'bucket'`".red unless s3_bucket.to_s.length > 0
        raise "No file path given, pass using `file: 'path''`".red unless file.to_s.length > 0
      
        s3_file_name =  s3_path + '/' + s3_file_name
        file_data = File.open(file, 'rb')

        file_url = self.upload_file(s3_bucket, s3_file_name, file_data)          

        Helper.log.info "Successfully uploaded ipa file to '#{file_url}'".green

        return file_url
      end

      def self.upload_file(bucket_name, file_name, file_data)

        s3 = Aws::S3::Resource.new(region:'us-east-1')
        obj = s3.bucket(bucket_name).object(file_name)
        file_url = obj.upload_file(file_data)

        # Return public url
        obj.public_url.to_s
      end

      #
      # NOT a fan of this as this was taken straight from Shenzhen
      # https://github.com/nomad/shenzhen/blob/986792db5d4d16a80c865a2748ee96ba63644821/lib/shenzhen/plugins/s3.rb#L32
      #
      # Need to find a way to not use this copied method
      #
      # AGAIN, I am not happy about this right now.
      # Using this for prototype reasons.
      #

      def self.description
        "Generates a plist file and uploads all to AWS S3"
      end

      def self.available_options
        [
          ['file', 'This is the file path'],
          ['bucket', 'This is s3 bucket'],
          ['region', 'This is s3 region'],
          ['acl', 'This is s3 Access Control Level'],
          ['path', 'This is s3 path after the bucket'],
          ['s3_file_name', 'This is s3 name of the file'],
        ]
      end

      def self.author
        "pconno3"
      end

      def self.is_supported?(platform)
        platform == :android || platform == :ios
      end
    end
  end
end

# rubocop:enable Metrics/AbcSize
