package com.alterdekim.hearthhack.component.processor.client.request.generic;

import com.alterdekim.Protocol;
import com.alterdekim.hearthhack.component.TcpConnection;
import com.alterdekim.hearthhack.util.BattleNetPacket;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import static com.alterdekim.hearthhack.util.GameUtilities.generateNotification;
import static com.alterdekim.hearthhack.util.GetAccountInfoRequest.NOTICES;


@Slf4j
public class ProfileNotices extends GenericParser {

    private Executor executor;

    private void sendNotices(TcpConnection conn) throws Exception {
        Protocol.ProfileNotices notices = Protocol.ProfileNotices.newBuilder()
                .build();

        Protocol.Notification n = generateNotification(212, notices.toByteString(), notices.getSerializedSize());

        Protocol.Header header = Protocol.Header.newBuilder()
                .setServiceId(4)
                .setMethodId(1)
                .setToken(conn.nextToken())
                .setObjectId(0)
                .setSize(n.getSerializedSize())
                .setStatus(0)
                .build();

        conn.send(new BattleNetPacket(header, n.toByteArray()));
    }

    @Override
    public void parseGenericRequest(int token, TcpConnection conn) throws Exception {
        if( this.executor != null ) this.executor.setRunning(false);
        this.executor = new Executor(conn);
        this.executor.start();
    }

    @Override
    public int getId() {
        return NOTICES.getValue();
    }


    @RequiredArgsConstructor
    private class Executor extends Thread {

        private final TcpConnection conn;
        @Setter
        private boolean isRunning = true;

        @Override
        public void run() {
            try {
                while(isRunning) {
                    Thread.sleep(7500);
                    sendNotices(conn);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }
}
