1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera.session;
18
19import java.io.File;
20import java.io.IOException;
21
22import javax.annotation.Nullable;
23
24/**
25 * Used to create temporary session files to be used by e.g. Photo Sphere to
26 * write into.
27 * <p>
28 * This file also handles the correct creation of the file and makes sure that
29 * it is available for writing into from e.g. native code.
30 */
31public class TemporarySessionFile {
32
33    private final SessionStorageManager mSessionStorageManager;
34    private final String mSessionDirectory;
35    private final String mTitle;
36
37    @Nullable
38    private File mFile;
39
40    public TemporarySessionFile(SessionStorageManager sessionStorageManager, String
41            sessionDirectory, String title) {
42        mSessionStorageManager = sessionStorageManager;
43        mSessionDirectory = sessionDirectory;
44        mTitle = title;
45        mFile = null;
46    }
47
48    /**
49     * Creates the file and all the directories it is in if necessary.
50     * <p>
51     * If file was prepared successfully, additional calls to this method will
52     * be no-ops and 'true' will be returned.
53     *
54     * @return Whether the file could be created and is ready to be written to.
55     */
56    public synchronized boolean prepare() {
57        if (mFile != null) {
58            return true;
59        }
60
61        try {
62            mFile = mSessionStorageManager.createTemporaryOutputPath(mSessionDirectory, mTitle);
63        } catch (IOException e) {
64            return false;
65        }
66        return true;
67    }
68
69    /**
70     * @return Whether the file has been created and is usable.
71     */
72    public synchronized boolean isUsable() {
73        return mFile != null;
74    }
75
76    /**
77     * @return The file or null, if {@link #prepare} has not be called yet or
78     *         preparation failed.
79     */
80    @Nullable
81    public synchronized File getFile() {
82        return mFile;
83    }
84
85}
86