package io.github.sdsstudios.ScoreKeeper.Fragment

import android.net.Uri
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.view.View
import io.github.sdsstudios.ScoreKeeper.R
import java.io.File

/**
 * Created by sethsch1 on 05/11/17.
 */

open class EditPlayerFragment : PlayerFragment() {
    companion object {
        const val ARG_PLAYER_ID = "player_id"

        fun showDialog(fragmentManager: FragmentManager, playerId: Long) {
            val bundle = Bundle()
            val fragment = EditPlayerFragment()

            bundle.putLong(ARG_PLAYER_ID, playerId)
            fragment.arguments = bundle

            fragment.show(fragmentManager, TAG)
        }
    }

    override var deleteIconOnDismiss: Boolean = false
    override val title by lazy { getString(R.string.title_edit_player) }
    override val posText by lazy { getString(R.string.pos_done) }

    private val mPlayerId by lazy { arguments!!.getLong(ARG_PLAYER_ID) }

    val player by lazy { playersViewModel.playerList.value!!.single { it.id == mPlayerId } }

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

        if (player.iconName != null) {
            outputUri = Uri.fromFile(File(
                    "${context!!.filesDir}/${player.iconName}"))

        }

        editTextName.setText(player.name)
        playerIconLayout.setIcon(player.iconName)
    }

    override fun setSelectedColorIndex() {
        selectedColor = player.color
    }

    override fun onPositiveButtonClick(iconName: String?) {
        player.name = editTextName.text.toString()
        player.iconName = iconName
        player.color = selectedColor
        playersViewModel.update(player)
    }
}