module CREAMVRB
  class Startup
    def self.load(upc)
      @enable_activemq = false
      browser_setup
      sign_in
      label = find_label_for_upc(upc)
      return if label.nil?
      puts "UPC: #{upc}\nLabel: #{label}"
      file_name, processing_status, video_present, thumbnail_present = find_filename(label, upc)
      return if file_name.nil?
      analyze_video(file_name, processing_status, video_present, thumbnail_present, upc)
    end

    def self.browser_setup
      @browser = Watir::Browser.new :chrome
      width = @browser.execute_script('return screen.width')
      height = @browser.execute_script('return screen.height')
      @browser.driver.manage.window.move_to(0, 0)
      @browser.driver.manage.window.resize_to(width, height)
    end

    def self.sign_in
      attempt_yml_login
      on(OA::BasePage) do |page|
        if page.sign_in_button?
          puts "Login credentials failed. ".red if page.login_error?
          page.username = ask "Enter OA username: "
          page.password = ask("Enter password: ") { |q| q.echo = "*" }
          page.sign_in_button
          @browser.goto ask "Paste 2-Factor Authorization link from your inbox and hit enter: "
          sign_in if page.login_error?
        end
      end
    end

    def self.attempt_yml_login
      on(OA::BasePage) do |page|
        page.goto unless page.current_url.include? page.page_url_value
        if File.exist?(Dir.pwd + "/../config/users.yml") && !page.login_error?
          puts "Attempting to log in using YML file."
          oa_login = YAML.load_file(Dir.pwd + "/../config/users.yml")
          page.username = oa_login["username"]
          page.password = oa_login["password"]
          page.sign_in_button
          @browser.goto ask "Paste 2-Factor Authorization link from your inbox and hit enter: "
        end
      end
    end

    def self.find_label_for_upc(upc)
      visit(OA::LabelCopySearchResultsPage, using_params: { upc: upc }) do |page|
        if page.results_element[1]["Label Company"].text == "No label copy releases found."
          if agree "No label copy releases found. Check to see if it's already in content? (yes/no): "
            return search_in_content(upc)
          else
            return
          end
        else
          return page.results_element[1]["Label Company"].link_element.href.split("=").last
        end
      end
    end

    def self.search_in_content(upc)
      on(OA::LabelCopySearchResultsPage) do |page|
        page.smartsearch_field = upc
        page.smartsearch_submit
      end
      on(OA::ViewReleasePage) do |page|
        if page.vendor_link?
          puts "This release is already in content.".green
          if agree "Do you want to continue checking the video in Workstation anyway? (yes/no): "
            return page.vendor_link_element.href.split("=").last
          else
            return
          end
        else
          puts "This UPC doesn't exist in the system.".red
          return
        end
      end
    end

    def self.find_filename(label, upc)
      visit(OA::LabelPage, using_params: { label_id: label }).login_as_admin
      @browser.wait_until { @browser.windows.size > 1 }
      @browser.windows.last.use
      on(Workstation::BasePage) do |page|
        page.search_field_element.element.when_present.set upc
        page.wait_until { page.search_result? }
        page.search_result_element.click
      end
      if agree "Flash is disabled. To enable it, visit \n"\
        "chrome://settings/content/siteDetails?site=https%3A%2F%2Fworkstation.theorchard.com\n"\
        "Allow Flash, refresh the page, and type 'yes' to continue: "
        @browser.wait_until { on(Workstation::ViewReleasePage).video_panel? }
      else
        return
      end
      on(Workstation::ViewReleasePage) do |page|
        if page.no_video_selected?
          puts "A video hasn't been selected for this release. Notify video ops to select or upload one.".red
          return
        end
        if page.video_container? && page.video_container == "Preview Not Available"
          video_present = false
        else
          video_present = page.video_container?
        end
        if page.thumbnail_element.element.src.include?("processing") ||
           page.thumbnail_element.element.src.include?("choosebelow")
          thumbnail_present = false
        else
          thumbnail_present = page.thumbnail?
        end
        return page.video_name.gsub("\n", ""), page.processing_status, video_present, thumbnail_present
      end
    end

    def self.analyze_video(file_name, processing_status, video_present, thumbnail_present, upc)
      puts "File name: #{file_name}\nProcessing status: #{processing_status}"\
        "\nVideo asset present? #{boolean_colors(video_present)}"\
        "\nThumbnail selected? #{boolean_colors(thumbnail_present)}"
      if processing_status == "Processing"
        check_for_mastered_file(processing_status, file_name, upc)
      end
      if video_present && !thumbnail_present
        puts "The video asset is present. Notify video ops to select a thumbnail.".green
      end
      if video_present && thumbnail_present
        puts "The assets are present. Notify video ops to deliver the release.".green
      end
      if (processing_status.include? "Complete") && !video_present
        check_for_mastered_file(processing_status, file_name, upc)
      end
    end

    def self.check_for_mastered_file(processing_status, file_name, upc)
      print "The status is \"#{processing_status}\""
      print " but some assets are missing" if processing_status.include? "Complete"
      if agree ". Check for existence of mastered file? (yes/no): "
        @browser.windows.first.use
        asset_id = on(OA::VideoDashboardPage).asset_id_for_mastered_file(file_name, upc)
        if asset_id.nil?
          puts "A video with the same file name was found but the UPC isn't correct. Notify video ops".red
          return
        end
        if asset_id.empty?
          puts "The mastered file is missing:\n"\
          " -Notify video ops to check if the video is currently in the temp folder.\n"\
          " -Check with systems to see if destination drive for mastered file is full.".red
          return
        else
          puts "Mastered asset ID: #{asset_id}"
          if agree "The mastered file is present. Do you want to send a re-encode message to ActiveMQ? (yes/no): "
            reencode_video(asset_id)
          else
            return
          end
        end
      else
        return
      end
    end

    def self.reencode_video(asset_id)
      visit(ActiveMQ::QueuesPage) do |page|
        @original_enqueued = page.queues_element["ORCD.ASSET.PREPROCESSOR"]["Messages Enqueued"].text.to_i
        page.queues_element["ORCD.ASSET.PREPROCESSOR"]["Operations"].link_element(text: "Send To").click
      end
      on(ActiveMQ::SendJMSMessagePage) do |page|
        page.message_body = "{\"asset_id\":\"#{asset_id}\"}" # {"asset_id":"9692492"}
        if @enable_activemq
          page.send_reencode_message
        else
          puts "Re-encoding via ActiveMQ is disabled for safety/testing. Set @enable_activemq to true to use.".red
        end
      end
      return unless @enable_activemq
      visit(ActiveMQ::QueuesPage) do |page|
        expect(page.queues_element["ORCD.ASSET.PREPROCESSOR"]["Messages Enqueued"].text.to_i).to be > @original_enqueued
      end
      puts "Re-encoding with asset ID #{asset_id}. Check back in half an hour."
    end

    def self.boolean_colors(true_or_false)
      if true_or_false
        true_or_false.to_s.green
      else
        true_or_false.to_s.red
      end
    end
  end
end
