/* Copyright (c) 1993 by Sanjay Ghemawat */

#ifndef _CALFILEH
#define _CALFILEH

/*
 * Calendar file encapsulation.
 */

#include "Time.h"

class Calendar;

class CalFile {
  public:
    CalFile(int readOnly, const char* name);
    ~CalFile();

    /*
     * Get file name.
     */
    char const* GetName();

    /*
     * Get associated calendar.
     */
    Calendar* GetCalendar();

    /*
     * Has calendar been modified.
     */
    int IsModified();

    /*
     * Called on each modification.
     */
    void Modified();

    enum CalFile_Result {
	Success,
	Cancel,
	Failure
	};

    /*
     * Write calendar out to file.
     * Return true only on success.
     */
    int Write();

    /*
     * Read calendar from file.
     */
    int Read();

    /*
     * Has file changed since last read?
     */
    int FileHasChanged();

    /*
     * Re-read file contents from disk.
     * Calendar is not changed on failure.
     * Returns nil on error, old calendar on success.
     */
    Calendar* ReRead();

    /*
     * Get last error.
     */
    static char const* LastError();
  protected:
    int readOnly;		/* Read-only mode? */
    const char* fileName;	/* Calendar file name */
    const char* backupName;	/* Backup file name */
    const char* tmpName;	/* Tmp file name */
    const char* dirName;	/* Directory name */

    Time    lastModifyTime;	/* Last calendar file modify time */
    int lastModifyValid;	/* Is lastModifyTime valid? */

    Calendar* calendar;		/* Volatile calendar state */

    int modified;		/* Has cal been modified since last write */

    /* Utility routines */
    static int GetModifyTime(char const*, Time&);

    /*
     * Update calendar readonly status.
     */
    void PerformAccessCheck();

    /* Read/Write calendar from/to named file */
    static Calendar* ReadFrom(const char*, int topLevel = 1);
    static int   WriteTo(Calendar*, const char*);

    /* Last error */
    static const char* lastError;
};

inline char const* CalFile::GetName() {
    return fileName;
}

inline Calendar* CalFile::GetCalendar() {
    return calendar;
}

inline int CalFile::IsModified() {
    return modified;
}

inline const char* CalFile::LastError() {
    return lastError;
}

#endif /* _CALFILEH */
