/**
 * ProjectLaogai
 *
 * Copyright 2019-2020  <seil0@mosad.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

package org.mosad.seil0.projectlaogai.controller

import android.content.Context
import android.content.Intent
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.IsoDep
import android.util.Log
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.codebutler.farebot.Utils
import com.codebutler.farebot.card.desfire.DesfireFileSettings
import com.codebutler.farebot.card.desfire.DesfireProtocol
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.preferences.Preferences
import java.lang.Exception

class NFCMensaCard {

    companion object {
        private const val className = "NFCMensaCard"
        private const val appId = 0x5F8415
        private const val fileId = 1

        /**
         * read the current balance and last payment from the mensa card
         * @param intent a nfc intent
         * @param context the context to show the dialog in
         */
        fun readBalance(intent: Intent, context: Context) {
            val tag: Tag? = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
            val isoDep = IsoDep.get(tag)
            try {
                isoDep.connect()

                val card = DesfireProtocol(isoDep)
                val settings = Utils.selectAppFile(card, appId, fileId)

                if (settings is DesfireFileSettings.ValueDesfireFileSettings) {
                    val data = try {
                        card.readValue(fileId)
                    } catch (ex: Exception) { 0 }

                    lookAtMe(context, data, settings.value).show()
                }
            } catch (ex: Exception) {
                Log.w(className,"could not connect to tag", ex)
            }

        }

        /**
         * generate the values for current balance and last payment
         * if the easter egg is active use schmeckles as currency
         * 0.0000075 = 1.11 / 148 / 1000 (dollar / shm / card multiplier)
         * @param context the context to access resources
         * @param currentRaw the raw card value of the current balance
         * @param lastRaw the raw card value of the last payment
         * @return the message containing all values
         */
        private fun lookAtMe(context: Context, currentRaw: Int, lastRaw: Int): MaterialDialog {
            val dialog = MaterialDialog(context)
                .customView(R.layout.dialog_mensa_credit)

            val current = if (!Preferences.oGiants) {
                String.format("%.2f €", (currentRaw.toFloat() / 1000))
            } else {
                String.format("%.4f shm", (currentRaw.toFloat() * 0.0000075))
            }

            val last = if (!Preferences.oGiants) {
                String.format("%.2f €", (lastRaw.toFloat() / 1000))
            } else {
                String.format("%.4f shm", (lastRaw.toFloat() * 0.0000075))
            }

            dialog.findViewById<TextView>(R.id.txtView_current).text = current
            dialog.findViewById<TextView>(R.id.txtView_last).text = context.resources.getString(R.string.mensa_last, last)
            
            return dialog
        }
    }
}