package com.beanpodtech.allinone.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.beanpodtech.allinone.jni.CounterNative;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TimeCounter {
    private static final String TAG = "lhs_TimeCounter";
    private static TimeCounter instance = null;
    //Record the history of video viewing
    private byte[] videoSecondBitMap = null;
    private FileUtil mFileUtil = null;
    //the context of this application
    private Context mContext = null;
    private boolean bitmapExsitFlag = false;
    private boolean nativeBitmapExsitFlag = false;
    private boolean serverBitmapExsitFlag = false;
    private int bitmapExsitState = Contants.BITMAP_UNEXSIT_STATE;
    private int nativeBitmapCheckState = Contants.BITMAP_UNCHECK_STATE;
    private int serverBitmapCheckState = Contants.BITMAP_UNCHECK_STATE;
    private String currentFileName = "";
    private int currentplayingTime = 0;
    private int counterForSaveNative = 0;
    private String videoId = "";
    private String courseId = "";


    public boolean isNativeBitmapExsitFlag() {
        return nativeBitmapExsitFlag;
    }

    public void setNativeBitmapExsitFlag(boolean nativeBitmapExsitFlag) {
        this.nativeBitmapExsitFlag = nativeBitmapExsitFlag;
    }

    public boolean isServerBitmapExsitFlag() {
        return serverBitmapExsitFlag;
    }

    public void setServerBitmapExsitFlag(boolean serverBitmapExsitFlag) {
        this.serverBitmapExsitFlag = serverBitmapExsitFlag;
    }

    public int getBitmapExsitState() {
        return bitmapExsitState;
    }

    public void setBitmapExsitState(int bitmapExsitState) {
        this.bitmapExsitState = bitmapExsitState;
    }

    public int getNativeBitmapCheckState() {
        return nativeBitmapCheckState;
    }

    public void setNativeBitmapCheckState(int nativeBitmapCheckState) {
        this.nativeBitmapCheckState = nativeBitmapCheckState;
    }

    public int getServerBitmapCheckState() {
        return serverBitmapCheckState;
    }

    public void setServerBitmapCheckState(int serverBitmapCheckState) {
        this.serverBitmapCheckState = serverBitmapCheckState;
    }

    public String getCurrentFileName() {
        return currentFileName;
    }

    public void setCurrentFileName(String currentFileName) {
        if (currentFileName != null && currentFileName.length() > 1) {
            this.currentFileName = currentFileName;
        } else {
            Log.e(TAG, "setCurrentFileName params is invalid");
        }
    }

    public int getCurrentplayingTime() {
        return currentplayingTime;
    }

    public void setCurrentplayingTime(int currentplayingTime) {
        this.currentplayingTime = currentplayingTime;
    }

    public int getCounterForSaveNative() {
        return counterForSaveNative;
    }

    public void setCounterForSaveNative(int counterForSaveNative) {
        this.counterForSaveNative = counterForSaveNative;
    }

    public String getVideoId() {
        return videoId;
    }

    public void setVideoId(String videoId) {
        this.videoId = videoId;
    }

    public String getCourseId() {
        return courseId;
    }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    private TimeCounter(Context context) {
        this.mContext = context;
        mFileUtil = new FileUtil();
    }

    public static TimeCounter getInstance(Context context) {
        if (instance == null) {
            synchronized (TimeCounter.class) {
                if (instance == null) {
                    instance = new TimeCounter(context);
                }
            }
        }
        return instance;
    }

    /**
     * @return
     */
    public byte[] getVideoSecondBitMap() {
        //
        return videoSecondBitMap;
    }

    /**
     *
     */
    public void setVideoSecondBitMap(byte[] bitMap) {
        //
        if (bitMap == null) {
            Log.e(TAG, "setVideoSecondBitMap params is null");
            return;
        }
        videoSecondBitMap = bitMap;
    }

    /**
     * @param videoDuration
     * @return
     */
    public byte[] createtVideoSecondBitMap(long videoDuration) {
        //
        int length = (int) (videoDuration / 8 + 1);
        videoSecondBitMap = new byte[length];
        return videoSecondBitMap;
    }

    public boolean createBitMapFile(byte[] bitMap, String fileName) {
        //params judgement
        File bitMapFile = new File(fileName);
        boolean result = mFileUtil.createFile(bitMapFile);
        if (!result) {
            return result;
        }
        //导入数据
        result = saveBitMapToFile(bitMap, fileName);

        return result;
    }

    public boolean saveBitMapToFile(byte[] bitMap, String fileName) {
        //params judgement

        boolean ret = mFileUtil.writeFile(bitMap, fileName);
        return ret;
    }

    /**
     * @param fileName
     * @return
     */
    public boolean isBitMapFileExist(String fileName) {
        //timeStamp : current time, and count time for example 2020-06-08 07:00:00

//        File sdDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                File f = new File(fileName);
                if (!f.exists()) {
                    return false;
                }

            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    public String getFileName(String userName, String videoId, long timeStamp) {

        if (userName == null || userName.length() < 1 || videoId == null || timeStamp == 0L) {
            Log.e(TAG, "getFileName params is invalid!");
            return null;
        }
        //generate file name
//        Log.d(TAG, "userName is " + userName + " vid :" + videoId);
        String fileName = userName + videoId + ".txt";
        String strFile = "";
        //get file directory
//        File sdDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = FileUtil.getPath(mContext, Environment.DIRECTORY_DOCUMENTS);
//            sdDir = Environment.getExternalStorageDirectory();
//            sdDir.toString();
//            Log.e(TAG, "sdcard path: " + sdDir);
            if (path == null) {
                Log.e(TAG, "sdcard is unmounted or file name is null");
                return null;
            }
            //strFile = sdDir.toString() + "/time/" + fileName;
            strFile = path + File.separator + timeToString(timeStamp) + File.separator + fileName;
            currentFileName = strFile;
            Log.d(TAG, "getFileName currentFileName " + currentFileName);
        }
        return strFile;
    }

    public String timeToString(long time) {
        if (time <= 0) {
            return null;
        }
        long currenttime = time;//System.currentTimeMillis();
        String timeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currenttime);
        String subStr = timeStr.substring(11, 13);
        int hour = Integer.valueOf(subStr);
        if (hour < 7) {//早上7点开始24小时内重复看课不计费
            currenttime -= 24 * 60 * 60 * 1000;
            timeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currenttime);
        }
        String fileTimeStr = timeStr.substring(0, 10);
        Log.d(TAG, "timestr is " + timeStr + " substr " + subStr + " hour " + hour + " filetimestr " + fileTimeStr);
        return fileTimeStr;
    }

    public long stringToTimestamp(String timestr) {
        if (timestr == null || timestr.equals("") || timestr.length() < 10) {
            return 0;
        }
        String timeTail = " 00:00:00";
        String tmp = timestr + timeTail;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;
        try {
            date = format.parse(tmp);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long timestamp = date.getTime();
        return timestamp;
    }
    //通过比较字符串去删除


    public static int getBetweenDay(Date date1, Date date2) {
        Calendar d1 = new GregorianCalendar();
        d1.setTime(date1);
        Calendar d2 = new GregorianCalendar();
        d2.setTime(date2);
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        System.out.println("days=" + days);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }

    public boolean isBitmapExsitFlag() {
        return bitmapExsitFlag;
    }

    public void setBitmapExsitFlag(boolean bitmapExsitFlag) {
        this.bitmapExsitFlag = bitmapExsitFlag;
    }

    public boolean isNeedCountFlag(int currentPosion) {
//        Log.d(TAG, "isNeedCountFlag current posion " + currentPosion);
        boolean needCountFlag = false;
        int index = currentPosion / 8;
        //int bitIndex = currentPosion % 8;
        if (videoSecondBitMap != null) {
//            Log.d(TAG, "isNeedCountFlag videoSecondBitMap[" + index + "] " + videoSecondBitMap[index]);
            byte tmp = CounterNative.bitRevese(videoSecondBitMap[index], currentPosion);
//            Log.d(TAG, "isNeedCountFlag tmp " + tmp);
            needCountFlag = (tmp != videoSecondBitMap[index]);
            if (needCountFlag) {
                videoSecondBitMap[index] = tmp;
            }
        }
        return needCountFlag;
    }

    public void reset() {

        bitmapExsitFlag = false;
        nativeBitmapExsitFlag = false;
        serverBitmapExsitFlag = false;
        bitmapExsitState = Contants.BITMAP_UNEXSIT_STATE;
        nativeBitmapCheckState = Contants.BITMAP_UNCHECK_STATE;
        serverBitmapCheckState = Contants.BITMAP_UNCHECK_STATE;
    }

}