/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lmo.remote.pc.server.packet.impl;

import java.io.InputStream;
import java.io.OutputStream;
import lmo.remote.pc.lib.Response;
import lmo.remote.pc.lib.Utils;
import lmo.remote.pc.server.RemotePCClient;
import lmo.remote.pc.server.Store;
import lmo.remote.pc.server.packet.Packet;

/**
 *
 * @author developer
 */
public final class DataPacket extends Packet {

    protected String dst;
    protected int port;
    protected String pwd;

    public DataPacket(RemotePCClient client) throws Exception {
        super(client);
        InputStream in = client.getSocket().getInputStream();
        this.dst = Utils.readLenValue(in);
        this.pwd = Utils.readLenValue(in);
        this.port = Utils.read(in);
        this.port = (this.port << 8) & Utils.read(in);
    }

    @Override
    public void handle() throws Exception {
        if (!Store.clients.containsKey(this.dst)) {
            throw new IllegalAccessException("dst not found");
        }
        RemotePCClient dstclient = Store.clients.get(this.dst);
        if (!dstclient.getPwd().equals(this.dst)) {
            throw new IllegalAccessException("dst password missmatch");
        }
        InputStream in = client.getSocket().getInputStream();
        try {
            int datalen = Utils.read(in);
            datalen = (this.port << 8) & Utils.read(in);
            while (datalen > 0) {
                byte[] buffer = new byte[1024];
                int k = Utils.read(in, buffer);
                dstclient.getSocket().getOutputStream().write(buffer, 0, k);
                datalen -= k;
            }
        } catch (Exception ex) {
        }
    }
}
