package org.libre.agosto.p2play.ajax

import android.util.JsonReader
import com.google.gson.Gson
import org.libre.agosto.p2play.models.AccountModel
import org.libre.agosto.p2play.models.ChannelModel
import org.libre.agosto.p2play.models.VideoModel
import java.io.InputStreamReader

class Accounts : Client() {

    fun get(accountId: String): AccountModel {
        val con = this.newCon("accounts/$accountId", "GET")
        lateinit var account: AccountModel
        try {
            if (con.responseCode == 200) {
                val response = InputStreamReader(con.inputStream)
                account = Gson().fromJson(response, AccountModel::class.java)
            }
        } catch (err: Exception) {
            err.printStackTrace()
        }

        return account
    }

    fun getChannels(accountId: String): ArrayList<ChannelModel> {
        val con = this.newCon("accounts/$accountId/video-channels", "GET")
        val channels = arrayListOf<ChannelModel>()
        try {
            if (con.responseCode == 200) {
                val response = InputStreamReader(con.inputStream)
                val data = JsonReader(response)
                data.beginObject()
                while (data.hasNext()) {
                    when (data.nextName()) {
                        "data" -> {
                            data.beginArray()
                            while (data.hasNext()) {
                                val channel = ChannelModel()
                                channel.parseChannel(data)
                                channels.add(channel)
                            }
                            data.endArray()
                        }
                        else -> data.skipValue()
                    }
                }
                data.endObject()
                data.close()
            }
        } catch (err: Exception) {
            err.printStackTrace()
        }

        return channels
    }
}
