package com.creyond.ecgdemo

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.SeekBar
import android.widget.Toast
import com.creyond.sdk.JsonUtil
import com.creyond.sdk.SharedUtil
import com.creyond.support.playback.Playbacker
import kotlinx.android.synthetic.main.activity_playback.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class PlaybackActivity : BaseActivity() {
    lateinit var playbacker: Playbacker

    @SuppressLint("SimpleDateFormat", "SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_playback)
        title = "报告结果"
        var record: String? = SharedUtil.getString(this, "record")
        if (record == null) {
            Toast.makeText(this, "暂无心电记录", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        var report = JsonUtil.fromJson(record, Report::class.java) as Report
        val path = report.path

        val file = File(path)
        if (!file.exists() || file.length() == 0L) {
            Toast.makeText(this, "文件不存在或文件大小为0", Toast.LENGTH_LONG).show()
            finish()
            return
        }
        playbacker = Playbacker.create(this, file, ecg_view)
        seek_bar.max = playbacker.totalPoints
        seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                playbacker.seek(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {

            }
        })
        playbacker.seek(0)

        tv_path.text = path.trim() + "加载成功"
        tv_start.text = "记录开始时间：\n" + SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(Date(report.startTime))
        tv_time.text = "记录时长（秒）：" + (report.stopTime - report.startTime) / 1000
        tv_min_heart_rate.text = "最小心率：" + format(report.minHeartRate) + "bpm"
        tv_heart_rate.text = "平均心率：" + format(report.heartRate) + "bpm"
        tv_max_heart_rate.text = "最大心率：" + format(report.maxHeartRate) + "bpm"
        tv_step.text = "步数：" + report.step
    }

    fun format(int: Int): Int {
        if (int > 0) {
            return int
        }
        return 0
    }

    override fun onResume() {
        super.onResume()

        ecg_view.resume()
    }


    override fun onPause() {
        super.onPause()
        ecg_view.pause()
    }
}
