<commit_before>require './setup'

Codec = require './codec'
Util = require './util'

class TSClient
  
  @logLevel = "info"

  # Setup values
  @params = Util.getURLParams()
  @params.port = 9876 if not @params.port # TODO: put this at a more permanent value
  
  @localMode = false
  
  @connected = false
  @wasConnected = false
  
  @clientId = undefined
  
  @expBroadcastSubscription = null
  @expServiceSubscription = null
  @lobbySubscription = null
  @userSubscription = null

  @connect_callback = undefined
  @disconnect_callback = undefined
  @error_callback = undefined  

  @quizneeded_cb = undefined
  @quizfail_cb = undefined
  @requestUsername_cb = undefined
  @enterLobby_cb = undefined
  @lobbyMessage_cb = undefined
  @preSubmit_cb = undefined

  @startExperiment_cb = undefined    
  @startRound_cb = undefined
  @timeLimit_cb = undefined
  @finishExperiment_cb = undefined
  @clientError_cb = undefined
  @broadcastMessage_cb = undefined
  @serviceMessage_cb = undefined

  @errorMessage_cb = undefined

  ###
  Pre-Experiment callbacks
  ###

  @QuizRequired: (callback) ->
    @quizneeded_cb = callback

  @QuizFailed: (callback) ->
    @quizfail_cb = callback
  
  @RequestUsername: (callback) ->
    @requestUsername_cb = callback
  
  @EnterLobby: (callback) ->
    @enterLobby_cb = callback
  
  @LobbyMessage: (callback) ->
    @lobbyMessage_cb = callback
  
  @PreSubmit: (callback) ->
    @preSubmit_cb = callback

  ###
  Experiment callback registration
  ###

  @StartExperiment: (callback) ->
    @startExperiment_cb = callback

  @StartRound: (callback) ->
    @startRound_cb = callback

  @TimeLimit: (callback) ->
    @timeLimit_cb = callback

  @FinishExperiment: (callback) ->
    @finishExperiment_cb = callback
    
  @ClientError: (callback) ->
    @clientError_cb = callback
    
  @BroadcastMessage: (callback) ->
    @broadcastMessage_cb = callback        

  @ServiceMessage: (callback) ->
    @serviceMessage_cb = callback        
      
  @ErrorMessage: (callback) ->
    @errorMessage_cb = callback
    
  ###
  Other functions
  ###

  @hitIsViewing: ->
    @params.assignmentId and @params.assignmentId is "ASSIGNMENT_ID_NOT_AVAILABLE"

  @initLocal: ->
    # Fake init for running demoes
    @localMode = true
    
    @params.hitId = "DEMO_HIT"
    @params.assignmentId = "DEMO_ASSIGNMENT"
    @params.workerId = "DEMO_WORKER"

  @init: (cookieName, contextPath) ->
    # Check for old state information
      
    stateCookie = (if org.cometd.COOKIE then org.cometd.COOKIE.get(cookieName) else null)
    state = (if stateCookie then org.cometd.JSON.fromJSON(stateCookie) else null)

    $.cometd.getExtension("reload").configure 
      cookieMaxAge: 10
    
    # connect listener
    $.cometd.addListener "/meta/connect", (message) =>
      # Available since 1.1.2
      return if $.cometd.isDisconnected()
      
      @wasConnected = @connected
      @connected = message.successful
      
      if not @wasConnected and @connected
        @connectionEstablished()
      else if @wasConnected and not @connected
        @connectionBroken()
    
    # handshake listener to report client IDs
    $.cometd.addListener "/meta/handshake", (message) =>
      if message.successful        
        @clientId = message.clientId
        @connectionInitialized()
      else
        @error_callback?()
    
    # disconnect listener
    $.cometd.addListener "/meta/disconnect", (message) ->
      @connected = false if message.successful
    
    # Initialize CometD - TODO un-fix the specific port
    cometURL = location.protocol + "//" + location.hostname + ":" + @params.port + contextPath + "/cometd"
    $.cometd.websocketEnabled = true
    $.cometd.init
      url: cometURL
      logLevel: @logLevel
    
    # Setup reload extension 
    $(window).unload =>
      if $.cometd.reload
        $.cometd.reload()
        
        # Save the application state only if the user was chatting
        if @wasConnected and @clientId
          expires = new Date()
          expires.setTime expires.getTime() + 5 * 1000
          org.cometd.COOKIE.set cookieName, org.cometd.JSON.toJSON(clientId: @clientId),
            "max-age": 5
            expires: expires

      else
        # TODO Do we need to always disconnect even on reload?
        $.cometd.disconnect()

  # CometD callbacks
  # First time connection
  @connectionInitialized: ->
    console.log "handshake successful"

  # (Re-)established connection, possibly first time
  @connectionEstablished: ->
    @connect_callback?()
    
    console.log "beginning connect"
    hitId = @params.hitId
    assignmentId = @params.assignmentId
    workerId = @params.workerId
    
    unless hitId
      alert "The HIT data was not loaded properly. Please reload the HIT from your dashboard."
    else<commit_msg>Added unsubscribe somewhere<commit_after>require './setup'

Codec = require './codec'
Util = require './util'

class TSClient
  
  @logLevel = "info"

  # Setup values
  @params = Util.getURLParams()
  @params.port = 9876 if not @params.port # TODO: put this at a more permanent value
  
  @localMode = false
  
  @connected = false
  @wasConnected = false
  
  @clientId = undefined
  
  @expBroadcastSubscription = null
  @expServiceSubscription = null
  @lobbySubscription = null
  @userSubscription = null

  @connect_callback = undefined
  @disconnect_callback = undefined
  @error_callback = undefined  

  @quizneeded_cb = undefined
  @quizfail_cb = undefined
  @requestUsername_cb = undefined
  @enterLobby_cb = undefined
  @lobbyMessage_cb = undefined
  @preSubmit_cb = undefined

  @startExperiment_cb = undefined    
  @startRound_cb = undefined
  @timeLimit_cb = undefined
  @finishExperiment_cb = undefined
  @clientError_cb = undefined
  @broadcastMessage_cb = undefined
  @serviceMessage_cb = undefined

  @errorMessage_cb = undefined

  ###
  Pre-Experiment callbacks
  ###

  @QuizRequired: (callback) ->
    @quizneeded_cb = callback

  @QuizFailed: (callback) ->
    @quizfail_cb = callback
  
  @RequestUsername: (callback) ->
    @requestUsername_cb = callback
  
  @EnterLobby: (callback) ->
    @enterLobby_cb = callback
  
  @LobbyMessage: (callback) ->
    @lobbyMessage_cb = callback
  
  @PreSubmit: (callback) ->
    @preSubmit_cb = callback

  ###
  Experiment callback registration
  ###

  @StartExperiment: (callback) ->
    @startExperiment_cb = callback

  @StartRound: (callback) ->
    @startRound_cb = callback

  @TimeLimit: (callback) ->
    @timeLimit_cb = callback

  @FinishExperiment: (callback) ->
    @finishExperiment_cb = callback
    
  @ClientError: (callback) ->
    @clientError_cb = callback
    
  @BroadcastMessage: (callback) ->
    @broadcastMessage_cb = callback        

  @ServiceMessage: (callback) ->
    @serviceMessage_cb = callback        
      
  @ErrorMessage: (callback) ->
    @errorMessage_cb = callback
    
  ###
  Other functions
  ###

  @hitIsViewing: ->
    @params.assignmentId and @params.assignmentId is "ASSIGNMENT_ID_NOT_AVAILABLE"

  @initLocal: ->
    # Fake init for running demoes
    @localMode = true
    
    @params.hitId = "DEMO_HIT"
    @params.assignmentId = "DEMO_ASSIGNMENT"
    @params.workerId = "DEMO_WORKER"

  @init: (cookieName, contextPath) ->
    # Check for old state information
      
    stateCookie = (if org.cometd.COOKIE then org.cometd.COOKIE.get(cookieName) else null)
    state = (if stateCookie then org.cometd.JSON.fromJSON(stateCookie) else null)

    $.cometd.getExtension("reload").configure 
      cookieMaxAge: 10
    
    # connect listener
    $.cometd.addListener "/meta/connect", (message) =>
      # Available since 1.1.2
      return if $.cometd.isDisconnected()
      
      @wasConnected = @connected
      @connected = message.successful
      
      if not @wasConnected and @connected
        @connectionEstablished()
      else if @wasConnected and not @connected
        @connectionBroken()
    
    # handshake listener to report client IDs
    $.cometd.addListener "/meta/handshake", (message) =>
      if message.successful        
        @clientId = message.clientId
        @connectionInitialized()
      else
        @error_callback?()
    
    # disconnect listener
    $.cometd.addListener "/meta/disconnect", (message) ->
      @connected = false if message.successful
    
    # Initialize CometD - TODO un-fix the specific port
    cometURL = location.protocol + "//" + location.hostname + ":" + @params.port + contextPath + "/cometd"
    $.cometd.websocketEnabled = true
    $.cometd.init
      url: cometURL
      logLevel: @logLevel
    
    # Setup reload extension 
    $(window).unload =>
      if $.cometd.reload
        $.cometd.reload()
        
        # Save the application state only if the user was chatting
        if @wasConnected and @clientId
          expires = new Date()
          expires.setTime expires.getTime() + 5 * 1000
          org.cometd.COOKIE.set cookieName, org.cometd.JSON.toJSON(clientId: @clientId),
            "max-age": 5
            expires: expires

      else
        # TODO Do we need to always disconnect even on reload?
        @unsubscribe()
        $.cometd.disconnect()

  # CometD callbacks
  # First time connection
  @connectionInitialized: ->
    console.log "handshake successful"

  # (Re-)established connection, possibly first time
  @connectionEstablished: ->
    @connect_callback?()
    
    console.log "beginning connect"
    hitId = @params.hitId
    assignmentId = @params.assignmentId
    workerId = @params.workerId
    
    unless hitId
      alert "The HIT data was not loaded properly. Please reload the HIT from your dashboard."
    else
{'fraction_non_alphanumeric': 0.10007244127082686, 'fraction_numerical': 0.003104625892579944, 'mean_word_length': 2.813733228097869, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4216376', 'n_tokens_mistral': 3014, 'n_tokens_neox': 2929, 'n_words': 704}