package com.hmg.hmgDr.globalErrorHandler

import android.os.Environment
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


object FileUtil {

    val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")

    fun pushLog(body: String?) {
        try {
            val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
            val time = SimpleDateFormat("HH:MM:SS", Locale.getDefault()).format(Date())
            val root =
                File(Environment.getExternalStorageDirectory(),"error_log_dir")
            // if external memory exists and folder with name Notes
            if (!root.exists()) {
                root.mkdirs() // this will create folder.
            }
            val oldFile = File(root, "error" + sdf.format(Date()).toString() + ".txt") // old file
            if (oldFile.exists()) oldFile.delete()
            val filepath = File(root, "error$date.txt") // file path to save
            val bufferedWriter = BufferedWriter(FileWriter(filepath, true))
            bufferedWriter.append("\r\n")
            bufferedWriter.append("\r\n").append(body).append(" Time : ").append(time)
            bufferedWriter.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        }
    }
}