package com.xixun.xixunplayer;

import android.content.ContentValues;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

import gnph.util.Digest;
import gnph.util.JSList;
import gnph.util.JSMap;
import gnph.util.URLConn;

public class LogThread extends Thread {

    public static ConcurrentLinkedQueue<ContentValues> rows = new ConcurrentLinkedQueue<>();

    Digest md5 = Digest.md5();

    public LogThread() {

    }
    
    @Override
    public void run() {
        long next = 0, nextDel = 0;
        while(true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }
            if(! Util.logOn) continue;
            var ms = System.currentTimeMillis();
            var row = rows.poll();
            if(row!=null) {
                try (var db = Util.openHelper.getWritableDatabase()) {
                    db.beginTransaction();
                    if(ms>=nextDel) {
                        nextDel = (ms - nextDel < 3000 ? nextDel : ms) + 3600000L;
                        var num = db.delete("log", "time<"+(ms-720*3600000L), null);
                        Util.println("  del overdue "+num);
                    }
                    var rowid = db.insert("log", null, row);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    Util.println("  rowid "+rowid);
                } catch (Exception e) {
                    Util.printStackTrace(e);
                }
            }
            if(ms>=next) {
                next = (ms-next < 3000 ? next : ms) + Util.cfg.intg("logUploadInterval", 60)*1000;
                var rows = new JSList<JSMap>();
                try (var db = Util.openHelper.getReadableDatabase()) {
                    var cursor = db.rawQuery("select * from log order by time", null);
                    while(cursor.moveToNext()) {
                        var pid = cursor.getString(2);
                        if(pid==null || pid.length()!=24) pid = md5.hexStr(cursor.getString(3).getBytes()).substring(0,24);
                        rows.add(new JSMap(
                                "beginAt", cursor.getLong(0),
                                "duration", cursor.getLong(1)/1000,
                                "pid", pid,
                                "name", cursor.getString(3),
                                "type", cursor.getString(4),
                                "lat", cursor.getDouble(5),
                                "lng", cursor.getDouble(6)
                        ));
                    }
                }
                Util.println("  Log Cnt "+rows.size());
                if(! rows.isEmpty()) {
                    Util.println(rows.last().toStr());
                    try {
                        var conn = new URLConn(Util.cfg.stnn("logUploadUrl")).timeout(15000);
                        conn.addHeader("Card-Id", Util.getCardId());
                        conn.forJson();
                        rows.write(conn.out());
                        var resp = conn.read();
                        Util.println("  Upload resp: "+resp);
                        if("OK".equals(resp) || "".equals(resp)) {
                            try (var db = Util.openHelper.getWritableDatabase()) {
                                db.beginTransaction();
                                var num = db.delete("log", "time<="+rows.last().lng("beginAt"), null);
                                db.setTransactionSuccessful();
                                db.endTransaction();
                                Util.println("  del Upled "+num);
                            } catch (Exception e) {
                                Util.printStackTrace(e);
                            }
                        }
                    } catch (Exception e) {
                        Util.printStackTrace(e);
                    }
                }
            }
        }
    }
}
