1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 * Copyright (C) 2016 Mopria Alliance, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.bips;
19
20import android.print.PrintJobId;
21
22import java.util.ArrayList;
23import java.util.List;
24
25/** Manages a job queue, ensuring only one job is printed at a time */
26class JobQueue {
27    private final List<LocalPrintJob> mJobs = new ArrayList<>();
28    private LocalPrintJob mCurrent;
29
30    /** Queue a print job for printing at the next available opportunity */
31    void print(LocalPrintJob job) {
32        mJobs.add(job);
33        startNextJob();
34    }
35
36    /** Cancel a previously queued job */
37    void cancel(PrintJobId id) {
38        // If a job hasn't started, kill it instantly.
39        for (LocalPrintJob job : mJobs) {
40            if (job.getPrintJobId().equals(id)) {
41                mJobs.remove(job);
42                job.getPrintJob().cancel();
43                return;
44            }
45        }
46
47        if (mCurrent.getPrintJobId().equals(id)) {
48            mCurrent.cancel();
49        }
50    }
51
52    /** Launch the next job if possible */
53    private void startNextJob() {
54        if (mJobs.isEmpty() || mCurrent != null) {
55            return;
56        }
57
58        mCurrent = mJobs.remove(0);
59        mCurrent.start(job -> {
60            mCurrent = null;
61            startNextJob();
62        });
63    }
64}
65