package net.pokeranalytics.android.ui.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import io.realm.Realm
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.activity.components.RequestCode
import net.pokeranalytics.android.ui.fragment.ImportFragment
import timber.log.Timber

class ImportActivity : PokerAnalyticsActivity() {

	private lateinit var fileURI: Uri

	enum class IntentKey(val keyName: String) {
		URI("uri")
	}

	companion object {

		/**
		 * Create a new instance for result
		 */
		fun newInstanceForResult(context: FragmentActivity, uri: Uri) {
			context.startActivityForResult(getIntent(context, uri), RequestCode.IMPORT.value)
		}

		private fun getIntent(context: Context, uri: Uri): Intent {
			val intent = Intent(context, ImportActivity::class.java)
			intent.putExtra(ImportActivity.IntentKey.URI.keyName, uri)
			return intent
		}
	}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)

		this.fileURI = intent.getParcelableExtra(ImportActivity.IntentKey.URI.keyName)

		setContentView(R.layout.activity_import)
		initUI()

	}

	override fun onStop() {
		super.onStop()

		// Updates the main thread instance with newly inserted data
		val realm = Realm.getDefaultInstance()
		realm.refresh()
		realm.close()
	}

	private fun initUI() {

		val fragmentTransaction = supportFragmentManager.beginTransaction()
		val fragment = ImportFragment()

		val fis = contentResolver.openInputStream(fileURI)
		Timber.d("Load fragment data with: $fis")
		fis?.let {
			fragment.setData(it)
		}

		fragmentTransaction.add(R.id.container, fragment)
		fragmentTransaction.commit()

	}

//	private fun requestPermission() {
//		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
//			ActivityCompat.requestPermissions(
//				this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_REQUEST_ACCESS_FINE_LOCATION
//			)
//		}
//	}
//
//	override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//		super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//	}

}