package com.jld.vod.utils

import com.jld.vod.R
import com.xuexiang.xui.utils.ResUtils.getString
import java.io.DataOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2019/11/26 10:09
 */
object DateUtils {

    /**
     * Date获取当前日期时间
     */
    fun getTime(date: Date?): String? {
        var simpleDateFormat: SimpleDateFormat = SimpleDateFormat("HH:mm")// HH:mm:ss
        simpleDateFormat.timeZone = TimeZone.getTimeZone("Asia/Shanghai")
        return simpleDateFormat.format(date)
    }

    fun getDate(date: Date?): String? {
        var simpleDateFormat: SimpleDateFormat = SimpleDateFormat("yyyy/MM/dd")// HH:mm:ss
        simpleDateFormat.timeZone = TimeZone.getTimeZone("Asia/Shanghai")
        return simpleDateFormat.format(date)
    }


    /**
     * 获取当前日期是星期几
     *
     * @param date
     * @return 当前日期是星期几
     */
    fun getWeekOfDate(date: Date?): String? {
        val weekDays =
            arrayOf(
                getString(R.string.lab_sunday),
                getString(R.string.lab_monday),
                getString(R.string.lab_tuesday),
                getString(R.string.lab_wednesday),
                getString(R.string.lab_thursday),
                getString(R.string.lab_friday),
                getString(R.string.lab_saturday)
            )
        val cal = Calendar.getInstance()
        cal.time = date
        var w = cal[Calendar.DAY_OF_WEEK] - 1
        if (w < 0) w = 0
        return weekDays[w]
    }

    /**
     * 设置系统时间
     * 【时间格式 yyyyMMdd.HHmmss】
     */
    fun setSystemDate(times: Long) {
        try {
            val datetimes = "yyyyMMdd.HHmmss" //时间格式
            var datetime =convertTimestamp2Date(times,datetimes)//格式化
            val process = Runtime.getRuntime().exec("su")//获取root权限

            val os = DataOutputStream(process.outputStream)
            os.writeBytes("setprop persist.sys.timezone GMT\n")
            os.writeBytes("/system/bin/date -s $datetime\n")
            os.writeBytes("clock -w\n")
            os.writeBytes("exit\n")
            os.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 时间戳按指定格式转化为日期（String）
     * @param timestamp
     * @param pattern
     * @return
     */
    fun convertTimestamp2Date(timestamp: Long, pattern: String): String {
        var simpleDateFormat = SimpleDateFormat(pattern);
        simpleDateFormat.timeZone = TimeZone.getTimeZone("Asia/Shanghai")
        return simpleDateFormat.format(Date(timestamp));
    }
}