package clnt;

import addr.addrEmpty;
import addr.addrIP;
import addr.addrType;
import cfg.cfgIfc;
import cfg.cfgVrf;
import cry.cryHashFcs16;
import ifc.ifcDn;
import ifc.ifcNull;
import ifc.ifcUp;
import ip.ipFwd;
import ip.ipFwdIface;
import ip.ipFwdTab;
import ip.ipPrt;
import pack.packHolder;
import user.userTerminal;
import util.bits;
import util.counter;
import util.logger;
import util.state;

/**
 * ax25 (rfc1226) client
 *
 * @author matecsaba
 */
public class clntAx25 implements Runnable, ipPrt, ifcDn {

    /**
     * protocol number
     */
    public static final int prot = 93;

    /**
     * upper layer
     */
    public ifcUp upper = new ifcNull();

    /**
     * target of tunnel
     */
    public String target = null;

    /**
     * vrf of target
     */
    public cfgVrf vrf = null;

    /**
     * source interface
     */
    public cfgIfc srcIfc = null;

    /**
     * sending ttl value, -1 means maps out
     */
    public int sendingTTL = 255;

    /**
     * sending tos value, -1 means maps out
     */
    public int sendingTOS = -1;

    /**
     * counter
     */
    public counter cntr = new counter();

    private ipFwd fwdCor;

    private addrIP fwdTrg;

    private ipFwdIface fwdIfc;

    private boolean working = true;

    public String toString() {
        return "ax25 to " + fwdTrg;
    }

    public addrType getHwAddr() {
        return new addrEmpty();
    }

    public void setFilter(boolean promisc) {
    }

    public state.states getState() {
        return state.states.up;
    }

    public void closeDn() {
        clearState();
    }

    public void flapped() {
        clearState();
    }

    public void setUpper(ifcUp server) {
        upper = server;
        upper.setParent(this);
    }

    public counter getCounter() {
        return cntr;
    }

    public int getMTUsize() {
        return 1400;
    }

    public long getBandwidth() {
        return 10000000;
    }

    public void sendPack(packHolder pck) {
        pck.merge2beg();
        if (fwdIfc == null) {
            return;
        }
        cryHashFcs16 sum = new cryHashFcs16();
        sum.init();
        pck.hashData(sum, 0, pck.dataSize());
        byte[] cb = sum.finish();
        pck.putCopy(cb, 0, 0, cb.length);
        pck.putSkip(cb.length);
        pck.merge2end();
        cntr.tx(pck);
        pck.putDefaults();
        if (sendingTTL >= 0) {
            pck.IPttl = sendingTTL;
        }
        if (sendingTOS >= 0) {
            pck.IPtos = sendingTOS;
        }
        pck.IPprt = prot;
        pck.IPsrc.setAddr(fwdIfc.addr);
        pck.IPtrg.setAddr(fwdTrg);
        fwdCor.protoPack(fwdIfc, pck);
    }

    /**
     * start connection
     */
    public void workStart() {
        new Thread(this).start();
    }

    /**
     * stop connection
     */
    public void workStop() {
        working = false;
        clearState();
    }

    public void run() {
        for (;;) {
            if (!working) {
                break;
            }
            try {
                clearState();
                workDoer();
            } catch (Exception e) {
                logger.traceback(e);
            }
            clearState();
            bits.sleep(1000);
        }
    }

    private void workDoer() {
        fwdTrg = userTerminal.justResolv(target, 0);
        if (fwdTrg == null) {
            return;
        }
        fwdCor = vrf.getFwd(fwdTrg);
        fwdIfc = null;
        if (srcIfc != null) {
            fwdIfc = srcIfc.getFwdIfc(fwdTrg);
        }
        if (fwdIfc == null) {
            fwdIfc = ipFwdTab.findSendingIface(fwdCor, fwdTrg);
        }
        if (fwdIfc == null) {
            return;
        }
        fwdCor.protoAdd(this, fwdIfc, fwdTrg);
        for (;;) {
            if (!working) {
                break;
            }
            bits.sleep(1000);
        }
    }

    private void clearState() {
        if (fwdIfc != null) {
            fwdCor.protoDel(this, fwdIfc, fwdTrg);
            fwdIfc = null;
        }
    }

    public int getProtoNum() {
        return prot;
    }

    public void closeUp(ipFwdIface iface) {
    }

    public void setState(ipFwdIface iface, state.states stat) {
    }

    public void recvPack(ipFwdIface rxIfc, packHolder pck) {
        int siz = pck.dataSize();
        if (siz < 3) {
            cntr.drop(pck, counter.reasons.tooSmall);
            return;
        }
        cryHashFcs16 sum = new cryHashFcs16();
        sum.init();
        pck.hashData(sum, 0, siz - 2);
        byte[] cb = sum.finish();
        byte[] cg = new byte[cb.length];
        pck.getCopy(cg, 0, siz - cg.length, cg.length);
        if (bits.byteComp(cg, 0, cb, 0, cg.length) != 0) {
            cntr.drop(pck, counter.reasons.badSum);
            return;
        }
        pck.setDataSize(siz - cg.length);
        cntr.rx(pck);
        upper.recvPack(pck);
    }

    public boolean alertPack(ipFwdIface rxIfc, packHolder pck) {
        return true;
    }

    public void errorPack(counter.reasons err, addrIP rtr, ipFwdIface rxIfc, packHolder pck) {
    }

}
