package com.xixun.xixunplayer;

import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Base64;

import gnph.util.JSMap;
import gnph.util.NumFmts;
import gnph.util.URLConn;

public class UDPThread extends Thread {

    public static void startSocket() {
        new Thread(()->{
            try (var socket = new DatagramSocket(33331)) {
                byte[] buffer = new byte[1024];
                var imgBuf = new ByteArrayOutputStream(10240);
                Util.println("\nAccepting");
                while(true) {
                    try {
                        var packet = new DatagramPacket(buffer, buffer.length);
                        socket.receive(packet);
                        var len = packet.getLength();
                        if(buffer[0]!=0x5A || buffer[len-1]!=(byte)0xA5 || buffer[1]<0x0a) continue;
                        var ins = MainActivity.ins;
                        if(ins==null) continue;
                        var view = ins.backView;
                        if(buffer[1]==0x0a) {
                            var buf = new StringBuilder(16);
                            if(buffer[2]!=0) buf.append(buffer[2]&0xff).append(":");

                            if(buf.length()!=0) buf.append(NumFmts.zz().format(buffer[3]&0xff)).append(":");
                            else if(buffer[3]!=0) buf.append(buffer[3]&0xff).append(":");
                            if(buf.length()!=0) buf.append(NumFmts.zz().format(buffer[4]&0xff));
                            else buf.append(buffer[4]&0xff);

                            if(buffer[7]>=1) buf.append(".").append(buffer[5]&0xff);
                            if(buffer[7]>=2) buf.append(buffer[6]&0xff);
                            var txt = buf.toString();
                            ins.runOnUiThread(() -> {
                                view.txts[0] = txt;
                                view.invalidate();
                            });
                        } else if(buffer[1]==0x0d) {
                            var txt = new String(buffer, 4, packet.getLength()-6);
                            ins.runOnUiThread(() -> {
                                view.paints[1].setTextSize(view.size2);
                                var tlen = view.paints[1].measureText(view.txts[1] = txt);
                                if(tlen > Util.screenWidth) view.paints[1].setTextSize(Util.screenWidth * view.size2 / tlen);
                                view.invalidate();
                            });
                        } else if(buffer[1]==0x0b) {
                            int size = buffer[3]&0xff;
                            if(buffer[2]==0) ins.runOnUiThread(() -> {
                                view.paints[0].setTextSize(size);
                                if(size + view.paints[1].getTextSize() > Util.screenHeight) view.paints[1].setTextSize(Util.screenHeight-size);
                                view.invalidate();
                            });
                            else if(buffer[2]==1) ins.runOnUiThread(() -> {
                                view.paints[1].setTextSize(view.size2 = size);
                                var tlen = view.paints[1].measureText(view.txts[1]);
                                if(tlen > Util.screenWidth) view.paints[1].setTextSize(Util.screenWidth * view.size2 / tlen);
                                view.invalidate();
                            });
                        } else if(buffer[1]==0x0f) {
                            int color = 0xff000000 | (buffer[3]&0xff)<<16 | (buffer[4]&0xff)<<8 | buffer[5]&0xff;
                            int idx = buffer[2];
                            if(idx==0||idx==1) ins.runOnUiThread(() -> {
                                view.paints[idx].setColor(color);
                                view.invalidate();
                            });
                        } else if(buffer[1]==0x0c) {
                            int val = buffer[2]&0xff;
                            var json = new JSMap();
                            json.put("_id", "SetBrightness");
                            json.put("_type", "SetBrightness");
                            json.put("brightnessPercentage", val*100/255);
                            var res = new URLConn("http://localhost:2016/settings").writeJson(json.toStr()).read();
                            Util.println(res);
                        } else if(buffer[1]==0x0e) {
                            //Util.println(new String(Hex.to(buffer, packet.getLength(), null)));
                            if(buffer[3]==1) imgBuf.reset();
                            imgBuf.write(buffer, 6, packet.getLength()-8);
                            if(buffer[3]==buffer[2]) {
                                var data = Base64.getDecoder().decode(imgBuf.toByteArray());
                                var fout = new FileOutputStream(Util.backImgFile);
                                fout.write(data);
                                fout.flush();
                                fout.getFD().sync();
                                fout.close();
                                imgBuf.reset();
                                var img = BitmapFactory.decodeFile(Util.backImgFile, Util.noScaled);
                                ins.runOnUiThread(() -> {
                                    view.cosImg = img;
                                    view.invalidate();
                                });
                            }
                        }
                    } catch (Throwable e) {
                        var ins = MainActivity.ins;
                        if(ins!=null) ins.runOnUiThread(() -> Util.makeText(ins, Util.toStr(e)).show());
                        Util.printStackTrace(e);
                    }
                }
            } catch (Throwable e) {
                var msg = e.getMessage();
                if(msg==null || ! msg.contains("in use")) MainActivity.ins.runOnUiThread(() -> Util.makeText(MainActivity.ins, Util.toStr(e)).show());
                Util.printStackTrace(e);
            }
        }).start();
    }
}
