package io.nexilis.service

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import io.newuniverse.SDK.nuSDKService
import io.nexilis.service.core.Data
import io.nexilis.service.core.optString
import io.nexilis.service.core.put
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

class Api {

    companion object {
        internal val lock = ReentrantLock()

        internal var condition: Condition? = null

        fun connect(account: String, activity: Activity) {
            Log.d(tag, "connect:$account")
            Thread {
                try {
                    activity.startService(Intent(activity, nuSDKService::class.java))
                    while (nuSDKService.getInstance(pass) == null || !nuSDKService.getInstance(pass)
                            .bCLMServiceReady()
                    ) {
                        Thread.sleep(100)
                    }
                    val preferences = activity.getSharedPreferences(
                        namePreference,
                        Context.MODE_PRIVATE
                    )
                    preferences.put(key = "api", value = account)
                    val random = String.format("%010d", SecureRandom().nextInt(999999))
                    val session = preferences.optString(
                        key = "session", default = random
                    )
                    Log.d(tag, "initConnection:$pass,$account,$activity,$session")
                    nuSDKService.getInstance(pass).initConnection(
                        pass,
                        account,
                        activity,
                        SdkCallback::class.java,
                        SdkCallback(),
                        "108.136.37.34",
                        42823,
                        session,
                        "09:00",
                        false,
                        "108.136.37.34:42823"
                    )
                    val pin = preferences.optString(key = "pin", default = "")
                    if (pin.isEmpty()) {
                        condition = lock.newCondition()
                        lock.withLock {
                            Log.d(tag, "wait connection")
                            condition?.let {
                                val await = it.await(15, TimeUnit.SECONDS)
                                preferences.put(key = "session", value = session)
                                Log.d(tag, "signup:start:$await")
                                val response = Service.sendSync(
                                    Data(
                                        code = "SUA01",
                                        status = System.nanoTime().toString(),
                                        bodies = mutableMapOf("Api" to account)
                                    )
                                )
                                Log.d(tag, "signup:response:$response")
                                response?.let { r ->
                                    Log.d(tag, "signup:isOk:${r.isOk()}")
                                    if (r.isOk()) {
                                        val p = r.bodies["A00"] ?: ""
                                        Log.d(tag, "signup:put:pin:$p")
                                        preferences.put(key = "pin", value = p)
                                        Log.d(tag, "signup:retrieve")
                                        Service.sendAsync(
                                            Data(
                                                code = "A050",
                                                status = System.nanoTime().toString(),
                                            )
                                        )
                                    }
                                }
                            }
                        }
                    }
                    Log.d(tag, "user pin: ${preferences.optString(key = "pin", default = "")}")
                } catch (e: Exception) {
                    Log.e(tag, e.message, e)
                }
            }.start()
        }
    }
}