package net.pokeranalytics.android.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.components.ResultCode
import net.pokeranalytics.android.ui.fragment.components.RealmFragment
import net.pokeranalytics.android.util.csv.CSVImporter
import net.pokeranalytics.android.util.csv.ImportException
import timber.log.Timber
import java.io.InputStream
import java.util.*
import kotlin.coroutines.CoroutineContext

class ImportFragment : RealmFragment() {

	val coroutineContext: CoroutineContext
		get() = Dispatchers.Main

	private lateinit var filePath: String
	private lateinit var inputStream: InputStream

	fun setData(path: String) {
		this.filePath = path
	}

	fun setData(inputStream: InputStream) {
		this.inputStream = inputStream
	}

	override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
		super.onCreateView(inflater, container, savedInstanceState)
		return inflater.inflate(R.layout.fragment_import, container, false)
	}

	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
		super.onViewCreated(view, savedInstanceState)

		this.startImport()
	}

	fun startImport() {

		var shouldDismissActivity = false

		GlobalScope.launch(coroutineContext) {

			val test = GlobalScope.async {
				val s = Date()
				Timber.d(">>> Start Import...")

				try {
					val csv = CSVImporter(inputStream)
					csv.start()
				} catch (e: ImportException) {
					shouldDismissActivity = true
				}
				val e = Date()
				val duration = (e.time - s.time) / 1000.0
				Timber.d(">>> Import ended in $duration seconds")

			}
			test.await()

			if (shouldDismissActivity) {

				activity?.let {
					it.setResult(ResultCode.IMPORT_UNRECOGNIZED_FORMAT.value)
					it.finish()
				}

			}

		}

	}

}