<commit_before>class KodingRouter extends KDRouter
  constructor:(defaultRoute)->
    @openRoutes = {}
    @openRoutesById = {}
    KD.getSingleton('contentDisplayController')
      .on 'ContentDisplayIsDestroyed', @cleanupRoute.bind @
    super getRoutes.call this

    @on 'AlreadyHere', ->
      new KDNotificationView title: "You're already here!"

  nicenames = {
    JTag      : 'Topics'
    JApp      : 'Apps'
    StartTab  : 'Develop'
  }

  getSectionName =(model)->
    sectionName = nicenames[model.bongo_.constructorName]
    if sectionName? then " - #{sectionName}" else ''

  handleRoute =(groupId, route)->
    console.log 'invoking a route by group id...'

  notFound =(route)->
    # defer this so that notFound can be called before the constructor.
    @utils.defer => @addRoute route, ->
      console.warn "Contract warning: shared route #{route} is not implemented."

  handleRoot =->
    KD.getSingleton("contentDisplayController").hideAllContentDisplays()
    if KD.isLoggedIn()
      @handleRoute @getDefaultRoute(), replaceState: yes
    else
      KD.getSingleton('mainController').doGoHome()

  cleanupRoute:(contentDisplay)->
    delete @openRoutes[@openRoutesById[contentDisplay.id]]
  
  go:(app, group, query, rest...)->
    pageTitle = nicenames[app] ? app
    @setPageTitle pageTitle
    unless group?
      log 'AAAAAA'
      appManager.openApplication app
    else
      log 'BBBBB'
      appManager.tell app, 'setGroup', group
    if Object.keys(query).length
      appManager.tell app, 'handleQuery', query

  stripTemplate =(str, konstructor)->
    {slugTemplate} = konstructor
    slugRe = /^(.+)?(#\{slug\})(.+)?$/
    re = RegExp slugTemplate.replace slugRe, (tmp, begin, slug, end)->
      "^#{begin ? ''}(.*)#{end ? ''}$"
    str.match(re)?[1]

  handleNotFound:(route)->

    status_404 = =>
      KDRouter::handleNotFound.call @, route

    status_301 = (redirectTarget)=>
      @handleRoute "/#{redirectTarget}", replaceState: yes

    KD.remote.api.JUrlAlias.resolve route, (err, target)->
      if err or not target? then status_404()
      else status_301 target

  getDefaultRoute:-> '/Activity'

  setPageTitle:(title="Koding")->
    document.title = title

  getContentTitle:(model)->
    {JAccount, JStatusUpdate, JGroup} = KD.remote.api
    @utils.shortenText (switch model.constructor
      when JAccount then "#{model.profile.firstName} #{model.profile.lastName}"
      when JStatusUpdate then model.body
      when JGroup then model.title
      else "#{model.title}#{getSectionName model}"
    ), 100

  openContent:(name, section, state, route)->
    @setPageTitle @getContentTitle state
    appManager.tell section, 'createContentDisplay', state, (contentDisplay)=>
      @openRoutes[route] = contentDisplay
      @openRoutesById[contentDisplay.id] = route

  loadContent:(name, section, slug, route)->
    KD.remote.api.JName.one {name: route}, (err, name)=>
      if err
        new KDNotificationView title: err?.message or 'An unknown error has occured.'
      else if name?
        {constructorName, usedAsPath} = name
        selector = {}
        konstructor = KD.remote.api[constructorName]
        slug = stripTemplate route, konstructor
        selector[usedAsPath] = slug
        konstructor?.one selector, (err, model)=>
          @openContent name, section, model, route
      else
        @handleNotFound route
    #konstructor = KD.getContentConstructor section
    # appManager.tell section, 'createContentDisplay', state, (contentDisplay)=>
    #   @openRoutes[route] = contentDisplay
    #   @openRoutesById[contentDisplay.id] = route

  createContentDisplayHandler:(section)->
    ({name, topicSlug}, state, route)=>
      contentDisplay = @openRoutes[route]
      if contentDisplay?
        KD.getSingleton("contentDisplayController")
          .hideAllContentDisplays contentDisplay
      else
        appManager.tell section, 'setGroup', name  if name?
        if state?
          @openContent name, section, state, route
        else
          @loadContent name, section, topicSlug, route

  getRoutes =->
    # Abbreviations used below:
    # "acc" is short for "accumulator"
    # "kv" is short for "key-value pair"
    # "sec" is short for "section"
    mainController = KD.getSingleton 'mainController'

    kv =(acc, sec)-> acc[sec[0]] = sec[1]; acc

    goToContent = 'Activity Apps Groups Members Topics'
      .split(' ')
      .map((sec)=> [sec, @createContentDisplayHandler sec])
      .reduce kv, {}

    goToSection = 'Account Activity Apps Groups Members StartTab Topics'
      .split(' ')
      .map((sec)-> [sec, ({params:{name}, query})-> @go sec, name, query])
      .reduce kv, {}

    routes =

      '/' : handleRoot
      ''  : handleRoot

      # verbs
      '/:name?/Login'     : ({params:{name}})-> mainController.doLogin name
      '/:name?/Logout'    : ({params:{name}})-> mainController.doLogout name; @clear()
      '/:name?/Register'  : ({params:{name}})-> mainController.doRegister name
      '/:name?/Join'      : ({params:{name}})-> mainController.doJoin name
      '/:name?/Recover'   : ({params:{name}})-> mainController.doRecover name

      # nouns
      '/:name?/Groups'                  : goToSection.Groups<commit_msg>work from home<commit_after>class KodingRouter extends KDRouter
  constructor:(defaultRoute)->
    @openRoutes = {}
    @openRoutesById = {}
    KD.getSingleton('contentDisplayController')
      .on 'ContentDisplayIsDestroyed', @cleanupRoute.bind @
    super getRoutes.call this

    @on 'AlreadyHere', ->
      new KDNotificationView title: "You're already here!"

  nicenames = {
    JTag      : 'Topics'
    JApp      : 'Apps'
    StartTab  : 'Develop'
  }

  getSectionName =(model)->
    sectionName = nicenames[model.bongo_.constructorName]
    if sectionName? then " - #{sectionName}" else ''

  handleRoute =(groupId, route)->
    console.log 'invoking a route by group id...'

  notFound =(route)->
    # defer this so that notFound can be called before the constructor.
    @utils.defer => @addRoute route, ->
      console.warn "Contract warning: shared route #{route} is not implemented."

  handleRoot =->
    KD.getSingleton("contentDisplayController").hideAllContentDisplays()
    if KD.isLoggedIn()
      @handleRoute @getDefaultRoute(), replaceState: yes
    else
      KD.getSingleton('mainController').doGoHome()

  cleanupRoute:(contentDisplay)->
    delete @openRoutes[@openRoutesById[contentDisplay.id]]
  
  go:(app, group, query, rest...)->
    pageTitle = nicenames[app] ? app
    @setPageTitle pageTitle
    unless group?
      appManager.openApplication app
    else
      appManager.tell app, 'setGroup', group
    if Object.keys(query).length
      appManager.tell app, 'handleQuery', query

  stripTemplate =(str, konstructor)->
    {slugTemplate} = konstructor
    slugRe = /^(.+)?(#\{slug\})(.+)?$/
    re = RegExp slugTemplate.replace slugRe, (tmp, begin, slug, end)->
      "^#{begin ? ''}(.*)#{end ? ''}$"
    str.match(re)?[1]

  handleNotFound:(route)->

    status_404 = =>
      KDRouter::handleNotFound.call @, route

    status_301 = (redirectTarget)=>
      @handleRoute "/#{redirectTarget}", replaceState: yes

    KD.remote.api.JUrlAlias.resolve route, (err, target)->
      if err or not target? then status_404()
      else status_301 target

  getDefaultRoute:-> '/Activity'

  setPageTitle:(title="Koding")->
    document.title = title

  getContentTitle:(model)->
    {JAccount, JStatusUpdate, JGroup} = KD.remote.api
    @utils.shortenText (switch model.constructor
      when JAccount then "#{model.profile.firstName} #{model.profile.lastName}"
      when JStatusUpdate then model.body
      when JGroup then model.title
      else "#{model.title}#{getSectionName model}"
    ), 100

  openContent:(name, section, state, route)->
    @setPageTitle @getContentTitle state
    appManager.tell section, 'createContentDisplay', state, (contentDisplay)=>
      @openRoutes[route] = contentDisplay
      @openRoutesById[contentDisplay.id] = route

  loadContent:(name, section, slug, route)->
    KD.remote.api.JName.one {name: route}, (err, name)=>
      if err
        new KDNotificationView title: err?.message or 'An unknown error has occured.'
      else if name?
        {constructorName, usedAsPath} = name
        selector = {}
        konstructor = KD.remote.api[constructorName]
        slug = stripTemplate route, konstructor
        selector[usedAsPath] = slug
        konstructor?.one selector, (err, model)=>
          @openContent name, section, model, route
      else
        @handleNotFound route
    #konstructor = KD.getContentConstructor section
    # appManager.tell section, 'createContentDisplay', state, (contentDisplay)=>
    #   @openRoutes[route] = contentDisplay
    #   @openRoutesById[contentDisplay.id] = route

  createContentDisplayHandler:(section)->
    ({name, topicSlug}, state, route)=>
      contentDisplay = @openRoutes[route]
      if contentDisplay?
        KD.getSingleton("contentDisplayController")
          .hideAllContentDisplays contentDisplay
      else
        appManager.tell section, 'setGroup', name  if name?
        if state?
          @openContent name, section, state, route
        else
          @loadContent name, section, topicSlug, route

  createGoTos =do->
    # Abbreviations used below:
    # "acc" is short for "accumulator"
    # "kv" is short for "key-value pair"
    # "sec" is short for "section"
    {isArray}   = Array
    kvMap       = (sec)-> [sec, fn sec]
    kvReduce    = (acc, sec)-> acc[sec[0]] = sec[1]; acc
    createGoTos = (names, fn)->
      names = names.split ' '  unless isArray names
      names.map(kvMap).reduce kvReduce, {}

  getRoutes =->

    mainController = KD.getSingleton 'mainController'

    # kv =(acc, sec)-> acc[sec[0]] = sec[1]; acc

    # goToContent = 'Activity Apps Groups Members Topics'
    #   .split(' ')
    #   .map((sec)=> [sec, @createContentDisplayHandler sec])
    #   .reduce kv, {}

    # goToSection = 'Account Activity Apps Groups Members StartTab Topics'
    #   .split(' ')
    #   .map((sec)-> [sec, ({params:{name}, query})-> @go sec, name, query])
    #   .reduce kv, {}

    goToContent = createGoTos(
      'Activity Apps Groups Members Topics'
      (sec)=> @createContentDisplayHandler sec
    )

    goToSection = createGoTos(
      'Account Activity Apps Groups Members StartTab Topics'
      (sec)-> ({params:{name}, query})-> @go sec, name, query
    )

    routes =

      '/' : handleRoot
      ''  : handleRoot

      # verbs
      '/:name?/Login'     : ({params:{name}})-> mainController.doLogin name
      '/:name?/Logout'    : ({params:{name}})-> mainController.doLogout name; @clear()
      '/:name?/Register'  : ({params:{name}})-> mainController.doRegister name
      '/:name?/Join'      : ({params:{name}})-> mainController.doJoin name
      '/:name?/Recover'   : ({params:{name}})-> mainController.doRecover name

      # nouns
      '/:name?/Groups'                  : goToSection.Groups
{'fraction_non_alphanumeric': 0.13484573502722322, 'fraction_numerical': 0.0034482758620689655, 'mean_word_length': 3.014936247723133, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 84, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7312037', 'n_tokens_mistral': 3429, 'n_tokens_neox': 3253, 'n_words': 814}