class window.MainCtrl extends BaseCtrl
    constructor: (@$scope, @$rootScope, @$http, @$state, @$injector, @Boards, @Dock, @Analytics, @Constants, @MixPanel) ->
        super()
        @nudgePreloader()
        @noBoards = false

        @getSite()

        if @Dock.hasUserToken()
            @getUser()
        else
            @getBoards()


    onSiteLoad: (data, headers) =>
        super(data, headers)

    getUser: =>
        console.log "getting user" if DEBUG
        #can't use $resource here, need a fresh instance in case token has changed
        @$http.get("#{apiPrefix}/v2/me.json", {headers: {'Authorization': @Dock.getUserToken()}})
        .success (data) =>
                @onGetUser(data)
        .error (error, status) =>
                @onGetUserError(error)

    onGetUser: (data) =>
        console.log "got user" if DEBUG
        @Dock.setUserInfo(data)
        @MixPanel.setUser(data)
        @getBoards()

    onGetUserError: (error) =>
        console.log error if DEBUG
        @showError()

    getBoards: =>
        if !@Dock.data.boardList
            @Boards.query(@onGetBoards, @onGetBoardsError)
        else
            console.log "got boards already" if DEBUG
            @progress()

    onGetBoards: (data) =>
        console.log "got boards" if DEBUG
        @Dock.setBoardList(data)
        @progress()

    onGetBoardsError: (error) =>
        console.log "error is #{error}" if DEBUG
        @showError()

    progress: =>
        numBoards = @Dock.getNumberOfBoards()
        console.log numBoards if DEBUG
        # if we found more than one board, let the user select a board
        @setForwardSlide()
        if numBoards > 1
            @noBoards = false
            console.log "more than 1 board" if DEBUG
            @$state.go(@Constants.routes.boards)
        else if numBoards == 1
            @noBoards = false
            console.log "1 board" if DEBUG
            # there's only one board, proceed to image upload
            # check if we know the user already, if not, proceed to enter name
            # set this board as the selected one
            @boardId = @Dock.boardList[0].id
            @Dock.setBoard(@Dock.boardList[0], {boardId: @boardId})
            if @Dock.data.userInfo
                console.log "got user info" if DEBUG
                @$state.go(@Constants.routes.upload, {boardId: @boardId})
            else
                @$state.go(@Constants.routes.user, {boardId: @boardId})
        else
            @noBoards = true

    showError: =>
        @$state.go(@Constants.routes.error)

MainCtrl.$inject = ["$scope", "$rootScope", "$http", "$state", "$injector", "Boards", "Dock", "Analytics", "Constants", "MixPanel"]

angular.module("shuttlerockApp").controller("MainCtrl", MainCtrl)