summaryrefslogtreecommitdiffstats
blob: 76856715d0581adf16933d73b3ee8b7497aedee4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*  Copyright (c) 2016, Isode Limited, London, England.
 *  All rights reserved.
 *
 *  Acquisition and use of this software and related materials for any
 *  purpose requires a written license agreement from Isode Limited,
 *  or a written license from an organisation licensed by Isode Limited
 *  to grant such a license.
 *
 */
package com.isode.stroke.whiteboard;

import java.util.ArrayList;
import java.util.List;

import com.isode.stroke.elements.WhiteboardOperation;

public class WhiteboardServer {
    
    private final List<WhiteboardOperation> operations_ = new ArrayList<WhiteboardOperation>();

    public void handleLocalOperationReceived(WhiteboardOperation operation) {
        operations_.add(operation);
    }
    
    public WhiteboardOperation handleClientOperationReceived(WhiteboardOperation newOperation) {
        
        if (operations_.isEmpty() || 
                newOperation.getParentID().equals(operations_.get(operations_.size()-1).getID())) {
            operations_.add(newOperation);
            return newOperation;
        }
        for (int i = (operations_.size()-1); i >= 0; i--) {
            WhiteboardOperation operation = operations_.get(i);
            while (newOperation.getParentID().equals(operation.getParentID())) {
                WhiteboardTransformer.Pair tResult = 
                        WhiteboardTransformer.transform(newOperation, operation);
                if (i == (operations_.size()-1)) {
                    operations_.add(tResult.second);
                    return tResult.second;
                }
                else {
                    newOperation = tResult.second;
                    i++;
                    operation = operations_.get(i);
                }
            }
        }
        return null;
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Server:\n");
        for (WhiteboardOperation op : operations_) {
            builder.append(op.getID());
            builder.append(" '");
            builder.append(op.getParentID());
            builder.append("' ");
            builder.append(op.getPos());
            builder.append("\n");
        }
        return builder.toString();
    }
    
    public void print() {
        System.out.println(this);
    }

}