/*
 *      Copyright (C) 2005-2012 Team XBMC
 *      http://www.xbmc.org
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This Program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with XBMC; see the file COPYING.  If not, see
 *  <http://www.gnu.org/licenses/>.
 *
 */

#include "DVDInputStreamFile.h"
#include "filesystem/File.h"
#include "filesystem/IFile.h"
#include "utils/log.h"
#include "utils/URIUtils.h"

/* PLEX */
#include "AdvancedSettings.h"
#include "GUISettings.h"
#include "Variant.h"
/* END PLEX */

using namespace XFILE;

CDVDInputStreamFile::CDVDInputStreamFile() : CDVDInputStream(DVDSTREAM_TYPE_FILE)
{
  m_pFile = NULL;
  m_eof = true;
}

CDVDInputStreamFile::~CDVDInputStreamFile()
{
  Close();
}

bool CDVDInputStreamFile::IsEOF()
{
  return !m_pFile || m_eof;
}

bool CDVDInputStreamFile::Open(const char* strFile, const std::string& content)
{
  if (!CDVDInputStream::Open(strFile, content))
    return false;

  m_pFile = new CFile();
  if (!m_pFile)
    return false;

  /* PLEX */
  unsigned int fileCacheSize = 0;
  if (m_item.IsPlexMediaServerLibrary() &&
      m_item.m_selectedMediaPart &&
      m_item.m_selectedMediaPart->HasProperty("size"))
  {
    CLog::Log(LOGDEBUG, "Cache selector: going to use cacheSize based on fileSize");
    uint64_t fileSize = m_item.m_selectedMediaPart->GetProperty("size").asUnsignedInteger();
    float percent = g_guiSettings.GetInt("cache.percent") / 100.0;
    uint64_t cacheSize = fileSize * percent;

    /* We need to resize the cache */
    cacheSize = std::min(cacheSize, (uint64_t)g_advancedSettings.m_smartCacheUpperLimit);
    fileCacheSize = cacheSize;
    CLog::Log(LOGDEBUG, "Cache selector: selected cacheSize: %lld", cacheSize);
  }
  else if (m_item.IsInternetStream()) // Internet video?
  {
    /* FIXME: selectedQuality never ends up here */
    unsigned int cacheSize = 1024 * 1024 * 50;
    CStdString selectedQuality = m_item.GetProperty("selectedQuality").asString();
    if (!selectedQuality.empty())
    {
      if (selectedQuality.Equals("1080p"))
        cacheSize = 1024 * 1024 * 100;
      if (selectedQuality.Equals("720p"))
        cacheSize = 1024 * 1024 * 70;
      else
        cacheSize = 1024 * 1024 * 50;
    }

    fileCacheSize = std::min(cacheSize, g_advancedSettings.m_smartCacheUpperLimit);
  }
  /* END PLEX */

  // open file in binary mode
  if (!m_pFile->Open(strFile, READ_TRUNCATED | READ_BITRATE | READ_CHUNKED | READ_CACHED, fileCacheSize)) // PLEX - added arguments here
  {
    delete m_pFile;
    m_pFile = NULL;
    return false;
  }

  if (m_pFile->GetImplemenation() && (content.empty() || content == "application/octet-stream"))
    m_content = m_pFile->GetImplemenation()->GetContent();

  m_eof = true;
  return true;
}

// close file and reset everyting
void CDVDInputStreamFile::Close()
{
  if (m_pFile)
  {
    m_pFile->Close();
    delete m_pFile;
  }

  CDVDInputStream::Close();
  m_pFile = NULL;
  m_eof = true;
}

int CDVDInputStreamFile::Read(BYTE* buf, int buf_size)
{
  if(!m_pFile) return -1;

  unsigned int ret = m_pFile->Read(buf, buf_size);

  /* we currently don't support non completing reads */
  if( ret <= 0 ) m_eof = true;

  return (int)(ret & 0xFFFFFFFF);
}

int64_t CDVDInputStreamFile::Seek(int64_t offset, int whence)
{
  if(!m_pFile) return -1;

  if(whence == SEEK_POSSIBLE)
    return m_pFile->IoControl(IOCTRL_SEEK_POSSIBLE, NULL);

  int64_t ret = m_pFile->Seek(offset, whence);

  /* if we succeed, we are not eof anymore */
  if( ret >= 0 ) m_eof = false;

  return ret;
}

int64_t CDVDInputStreamFile::GetLength()
{
  if (m_pFile)
    return m_pFile->GetLength();
  return 0;
}

bool CDVDInputStreamFile::GetCacheStatus(XFILE::SCacheStatus *status)
{
  if(m_pFile && m_pFile->IoControl(IOCTRL_CACHE_STATUS, status) >= 0)
    return true;
  else
    return false;
}

BitstreamStats CDVDInputStreamFile::GetBitstreamStats() const
{
  if (!m_pFile)
    return m_stats; // dummy return. defined in CDVDInputStream

  if(m_pFile->GetBitstreamStats())
    return *m_pFile->GetBitstreamStats();
  else
    return m_stats;
}

int CDVDInputStreamFile::GetBlockSize()
{
  if(m_pFile)
    return m_pFile->GetChunkSize();
  else
    return 0;
}

void CDVDInputStreamFile::SetReadRate(unsigned rate)
{
  unsigned maxrate = rate + 1024 * 1024 / 8;
  if(m_pFile->IoControl(IOCTRL_CACHE_SETRATE, &maxrate) >= 0)
    CLog::Log(LOGDEBUG, "CDVDInputStreamFile::SetReadRate - set cache throttle rate to %u bytes per second", maxrate);
}
