# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

platform :ios do
  
  # MARKETING: RECORD PREVIEWS. 
  desc "Generate localized preview"
  lane :previews do |options|

    cacheDirectory = '~/Library/Caches/tools.fastlane/screenshots'

    # Delete all existing videos.
    #mp4_file_paths = Find.find('../videos').select { |p| /.*\.mp4$/ =~ p}
    #for mp4_file_path in mp4_file_paths
    #  File.delete(mp4_file_path)
    #end

    # Ensure that caching folder for screenshots and recording flags exists
    Dir.mkdir(File.expand_path(cacheDirectory)) unless Dir.exist?(File.expand_path(cacheDirectory))

    # Setup listeners for starting and ending recording
    fastlane_require 'listen'
    path = nil
    process = nil
    trimming_time_dictionary = {}
    recordingListener = Listen.to(File.expand_path(cacheDirectory), only: /\.txt$/) do |modified, added, removed|
      if (!added.empty?) && File.basename(added.first) == 'recordingFlag.txt'
        recording_flag_path = added.first
        path = File.read(recording_flag_path)
        # Start recording of current simulator to path determined in recordingFlag.txt
        process = IO.popen("xcrun simctl io booted recordVideo '#{path}'")
      end
      if (!removed.empty?) && File.basename(removed.first) == 'recordingFlag.txt'
        pid = process.pid
        # Stop recording by killing process with id pid
        Process.kill("INT", pid)
        trimming_flag_path = File.expand_path(cacheDirectory + '/trimmingFlag.txt')
        trimming_time = File.read(trimming_flag_path)
        # Storing trimming time determined in trimmingFlag.txt for recorded video (necessary due to initial black simulator screen after starting recording)
        trimming_time_dictionary[path] = trimming_time
      end
    end

    # Build and run tests.
    recordingListener.start
    sh("cd .. && fastlane snapshot && cd fastlane")
    recordingListener.stop

    # Wait for fastlane to finish.
    sleep(3)

    # Modify videos.
    # Guidelines here https://help.apple.com/app-store-connect/?lang=en/#/dev4e413fcb8.
    mp4_file_paths = Find.find('./videos').select { |p| /.*\.mp4$/ =~ p}
    for mp4_file_path in mp4_file_paths

      # Don't alter "final" videos.
      if mp4_file_path.end_with? "-final.mp4"
        next
      end

      trimming_time = trimming_time_dictionary[mp4_file_path]
      final_path = mp4_file_path.chomp('.mp4') + '-final.mp4'

      # Modifier: rotate 90° clockwise if iPad.
      rotation = ""
      if mp4_file_path.include? "iPad"
         rotation = "transpose=2,"
      end

      # Modifier: resize for App Store guidelines.
      resizer = "886:1920"
      if mp4_file_path.include? "iPad Pro"
        resizer = "1600:1200"
      elsif mp4_file_path.include? "iPad mini"
        resizer = "1200:900"
      elsif mp4_file_path.include? "iPhone" and mp4_file_path.include? "Pro"
        resizer = "886:1920"
      elsif mp4_file_path.include? "iPhone 8" or mp4_file_path.include? "iPhone SE"
        resizer = "1080:1920"
      end
      
      sh("ffmpeg \
          -f lavfi -i anullsrc=channel_layout=stereo -i '#{mp4_file_path}' -shortest -movflags frag_keyframe+empty_moov -f mp4 - | ffmpeg -i '/dev/stdin' \
          -ss '#{trimming_time}' \
          -vf #{rotation}scale=#{resizer},setsar=1 \
          -ar 44100 -ab 256k -r 30 -crf 22 -profile:v main -pix_fmt yuv420p -y -max_muxing_queue_size 1000 \
          '#{final_path}'")

      File.delete(mp4_file_path)
      
    end

    # Delete .png screenshots.
    screenshots_paths = Find.find('./videos').select { |p| /.*\.png$/ =~ p}
    for screenshot_path in screenshots_paths
      File.delete(screenshot_path)
    end
    File.delete("./videos/screenshots.html")
    
  end

end
