package brs.visitor;

import brs.*;
import lrs.*;

/**
 * This visitor returns an LRStruct that contains the root and all the nodes in
 * the right subtree in a pre-order fashion, and makes the left subtree this tree.
 **/
/*
tree=
1
|_ 2
|  |_ 3
|  |  |_ []
|  |  |_ []
|  |_ 4
|     |_ []
|     |_ []
|_ 5
   |_ 6
   |  |_ []
   |  |_ []
   |_ 7
      |_ []
      |_ []
clipRight --> (1 5 6 7)

tree=
2
|_ 3
|  |_ []
|  |_ []
|_ 4
   |_ []
   |_ []
clipRight --> (2 4)

tree=
3
|_ []
|_ []
trim --> (3)

tree=
[]

trim --> ()

tree=
[]
*/
public class BRSClipRight implements IVisitor {
    public static final BRSClipRight Singleton = new BRSClipRight();
    private BRSClipRight() {}
    
    // STUDENT TO COMPLETE
    public Object emptyCase(BiTree host, Object... nu) {
        return new LRStruct();
    }
    
    public Object nonEmptyCase(final BiTree outerHost, Object... nu) {
        LRStruct lrs = (LRStruct)outerHost.getRightSubTree().execute(new IVisitor() {
            public Object emptyCase(BiTree host, Object... inp) {
                return inp[0];
            }
            public Object nonEmptyCase(BiTree host, final Object... inp) {
                LRStruct l = (LRStruct)host.getLeftSubTree().execute(this, host.getRightSubTree().execute(this, inp));
                l.insertFront(host.getRootDat());
                return l;
            }
        }, new LRStruct());
        lrs.insertFront(outerHost.getRootDat());
        outerHost.getLeftSubTree().execute(new IVisitor() {
            public Object emptyCase(BiTree host, Object... inp) {
                 // make this tree empty
                outerHost.setLeftSubTree(new BiTree());
                outerHost.setRightSubTree(new BiTree());
                outerHost.remRoot();
                return null;
            }
            public Object nonEmptyCase(BiTree host, final Object... inp) {
                outerHost.setRootDat(host.getRootDat());
                outerHost.setLeftSubTree(host.getLeftSubTree());
                outerHost.setRightSubTree(host.getRightSubTree());
                return null;
            }
        });
        return lrs;
    }    
}

