module Scoutui::Commands

  class UpdateUrl < Command


    def execute(drv, _e=nil)
      @drv=drv if !drv.nil?

      _duration=nil

      _req = Scoutui::Utils::TestUtils.instance.getReq()

      baseUrl = Scoutui::Base::UserVars.instance.getHost()

      url = @cmd.match(/navigate\s*\((.*)\)/i)[1].to_s.strip
      Scoutui::Logger::LogMgr.instance.commands.debug __FILE__ + (__LINE__).to_s + " url => #{url}"  if Scoutui::Utils::TestUtils.instance.isDebug?

      _relativeUrl = url.strip.start_with?('/')


      if _relativeUrl
        Scoutui::Logger::LogMgr.instance.commands.debug __FILE__ + (__LINE__).to_s + " [relative url]: #{baseUrl} with #{url}"  if Scoutui::Utils::TestUtils.instance.isDebug?
        url = baseUrl + url
      end


      normUrl=Scoutui::Base::UserVars.instance.normalize(url)

 #     url = Scoutui::Base::UserVars.instance.get(url)
      Scoutui::Logger::LogMgr.instance.debug __FILE__ + (__LINE__).to_s + " get(): #{normUrl}"


      Scoutui::Logger::LogMgr.instance.commands.debug __FILE__ + (__LINE__).to_s + " | translate : #{normUrl}"

      _rc=false
      begin
        Scoutui::Logger::LogMgr.instance.debug __FILE__ + (__LINE__).to_s + " navigate.to(#{url})"

        _start=Time.now
        @drv.navigate.to(normUrl)
        _stop=Time.now
        _duration=_stop - _start

        Scoutui::Logger::LogMgr.instance.debug __FILE__ + (__LINE__).to_s + " Perf navigate to #{normUrl} : #{_duration}"
        Scoutui::Logger::LogMgr.instance.debug __FILE__ + (__LINE__).to_s + " => title #{@drv.title.to_s}"
        _rc=true
      rescue Selenium::WebDriver::Error::UnhandledAlertError => ex
        Scoutui::Logger::LogMgr.instance.info __FILE__ + (__LINE__).to_s + " Alert : #{ex.message}"
        _rc=true
      rescue => ex
        Scoutui::Logger::LogMgr.instance.warn __FILE__ + (__LINE__).to_s + " Error during processing: #{ex.class} - #{ex.message}"
        Scoutui::Logger::LogMgr.instance.warn "Backtrace:\n\t#{ex.backtrace.join("\n\t")}"
      end


      _testcase = Scoutui::Utils::TestUtils.instance.getTC() || "navigate"

      Testmgr::TestReport.instance.getReq(_req).testcase(_testcase).add(_rc, Scoutui::Base::UserVars.instance.normalize("Verify navigate to url #{normUrl}"), _duration)


      Scoutui::Logger::LogMgr.instance.debug __FILE__ + (__LINE__).to_s + " update_url => #{_rc}"

      setResult(_rc)

    end

  end



end