     @store  = new Readmill.Store
     @client = new Readmill.Client @options
 
+    @view.subscribe "connect", @connect
+
     token = options.accessToken || @store.get "access-token"
     @connected(token, silent: true) if token
     @unsaved = []

  constructor: () ->
    super jQuery(@template)

  login: (user) ->
    @updateUser(user) if user
    @element.addClass @classes.loggedIn
    this

  logout: () ->
    @element = @element.replaceWith jQuery(@template)
    this

  updateUser: (user) ->
    if user
      @element.find(".annotator-readmill-fullname").escape(user.fullname)
      @element.find(".annotator-readmill-username").escape(user.username)
      @element.find(".annotator-readmill-avatar").attr("href", user.permalink_url)
              .find("img").attr("src", user.avatar_url)
    this

  updateBook: (book) ->
    if book
      @element.find(".annotator-readmill-book").escape(book.title or "Loading book…")
    this

  render: ->
    @updateBook()
    @updateUser()
    @element

class Client
  @API_ENDPOINT: "https://api.readmill.com"

    obj

class View extends Annotator.Plugin
  events:
    ".annotator-readmill-connect a click": "_onConnectClick"
    ".annotator-readmill-logout a click":  "_onLogoutClick"

  classes:
    loggedIn: "annotator-readmill-logged-in"

