package utils

import (
    "bytes"
    "io"
    "os"
    "path/filepath"
    "time"
)


func CacheStream( path string, readStream func() ( io.ReadCloser, error ), expires int ) ( *bytes.Buffer, error ) {

    cache, err := os.Stat( path )

    // Check if cache exists and not expired
    if err == nil {
        expired := cache.ModTime().Add( 60 * 1e9 )
        if time.Now().Before( expired ) {
            f, err := os.Open( path )
            if err == nil {
                defer f.Close()
                writeBuff := bytes.NewBuffer( []byte{} )
                _, err = io.Copy( writeBuff, f )
                if err == nil {
                    return writeBuff, nil
                }
            }
        }
    }

    err = os.MkdirAll( filepath.Dir( path ), 0750 )
    if err != nil {
        return nil, err
    }

    writeBuff := bytes.NewBuffer( []byte{} )

    // Get the reader that return new data
    s, err := readStream()
    if err != nil {
        return nil, err
    }

    defer s.Close()

    _, err = io.Copy( writeBuff, s )
    if err != nil {
        return nil, err
    }

    f, err := os.OpenFile( path, os.O_CREATE | os.O_WRONLY | os.O_TRUNC, 0644 )
    if err != nil {
        return nil, err
    }

    defer f.Close()

    data := writeBuff.Bytes()
    _, err = io.Copy( f, bytes.NewReader( data ) )
    if err != nil {
        return nil, err
    }

    return writeBuff, nil
}
