remote = require('remote')

app = window.app
wsManager = window.wsManager

app.controller 'AboutViewController', ($scope, $rootScope, $timeout) ->
    VIEWS =
        ABOUT: 1
        LOGIN: 2


    init = ->
        $scope.VIEWS = VIEWS
        $scope.setView VIEWS.ABOUT
        $scope.setFootMessage ''
        $scope.formLogin = null
        $scope.model =
            email: $rootScope.getEmail()
            password: ''
        if $rootScope.isVIP()
            $scope.model.email = $rootScope.getEmail()
            $scope.setView VIEWS.ABOUT

    wsManager.addMessageHandler (message) ->
        switch message.event
            when wsManager.EVENT_RES.CREATE_AUTH
                console.log 'CREATE_AUTH',JSON.stringify message
                if message.success
                    $rootScope.setEmail $scope.model.email
                    $scope.setView VIEWS.ABOUT
                    $scope.setFootMessage ''
                else
                    $scope.setFootMessage '验证失败'
                    $rootScope.setEmail ''
                $timeout (->$rootScope.$apply()), 0
            else
                return

    $scope.setView = (view) ->
        $scope.currentView = view
        $scope.setFootMessage ''

    $scope.IsView = (view) ->
        return $scope.currentView == view

    createAuth = (email, password) ->
        wsManager.ws.send wsManager.EVENT_REQ.CREATE_AUTH(email, password).json

    $scope.submitLogin = ->
        console.log $scope.model
        $scope.setFootMessage("")
        return  $scope.setFootMessage('用户名或密码无效') if $scope.formLogin.$invalid
        createAuth($scope.model.email, $scope.model.password)

    $scope.logout = ->
        $scope.model.email = ''
        $scope.model.password = ''
        createAuth('', '')

    $scope.setFootMessage = (message) ->
        $scope.footMessage = message

    # modal show hide
    aboutModal = $scope.$parent.aboutModal
    aboutModal.setOnShow ->
        $scope.duckWinkVideo.play()
        if aboutModal.redirectToLogin
            $scope.setView(VIEWS.LOGIN)
            aboutModal.redirectToLogin = false

    aboutModal.setOnHide ->
        $scope.duckWinkVideo.pause()
    $scope.aboutModal = aboutModal
    # -- modal show hide

    init()
    console.log "[AboutViewController] init ok"