/* eslint-disable */

let converse = function ($http) {
    let apiUrl = 'http://localhost:8081'

    // Initialize Firebase
    let config = {
        apiKey: "AIzaSyCUq3YUcVzUkUpIyXmpGd_L43JX_xKyq64",
        authDomain: "tugasbesar3-2017.firebaseapp.com",
        databaseURL: "https://tugasbesar3-2017.firebaseio.com",
        projectId: "tugasbesar3-2017",
        storageBucket: "tugasbesar3-2017.appspot.com",
        messagingSenderId: "948017499394"
    }

    class Account {
        constructor(id) {
            this.id = id
            this.onChat = (msg) => {
                console.log(msg)
            }
        }

        async initAsync() {
            firebase.initializeApp(config)
            let messaging = firebase.messaging()

            messaging.onMessage(msg => {
                console.log(msg)
                this.onChat(msg.data.message)
            })

            try {
                await messaging.requestPermission()
            } catch (e) {
                console.log(e)
                alert('Please grant notification permission.')
            }

            try {
                let data = JSON.stringify({
                    'token': await messaging.getToken()
                })
                console.log(data)

                let response = await $http.post(`${apiUrl}/chat/${this.id}/init`, data)
                return response.data.chats
            } catch (e) {
                console.log(e)
                alert('Unable to initialize chat service.')
            }
        }

        chatAsync(message) {
            let data = JSON.stringify({
                'message': message
            })

            return $http.post(`${apiUrl}/chat/${this.id}`, data)
        }
    }

    class Driver extends Account {
        async waitAsync(timeout) {
            let response = await $http.post(`${apiUrl}/driver/${this.id}/wait`, '', {
                timeout: timeout
            })

            return response.data.user_id
        }
    }

    class User extends Account {
        async checkAsync(ids) {
            let data = JSON.stringify({
                'driver_ids': ids
            })

            let response = await $http.post(`${apiUrl}/driver/check`, data)
            return response.data.driver_ids
        }

        pickAsync(id) {
            let data = JSON.stringify({
                'user_id': this.id
            })

            return $http.post(`${apiUrl}/driver/${id}/pick`, data)
        }
    }

    return {
        Driver: Driver,
        User: User
    }
}