/*****************************************************************************
Open Source MIT License

Copyright (c) 2017 Matthew Ahmed

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*****************************************************************************/

// FileCopyDlg.cpp : implementation file
//

#include "Headers.h"
#include "JpgFolders.h"
#include "Settings.h"
#include "FileCopyDlg.h"


// CFileCopyDlg dialog

//IMPLEMENT_DYNAMIC(CFileCopyDlg, CDialog)
CFileCopyDlg::CFileCopyDlg(CJpgFolders * pJpf, INT nCountToCopy, INT * nArrToCopy,
                           LPCTSTR sSrcJpgName, LPCTSTR sTgtJpgName,
                           HINSTANCE hInst, CZDialog * pOwner, LPCTSTR sCapt1,
                           LPCTSTR sCapt2, CSettings * pSet)
  : CZDialog(CFileCopyDlg::IDD, sCapt1, pOwner, pSet)
{
  m_pJpf = pJpf;
  m_nCountToCopy = nCountToCopy;
  m_nArrToCopy = nArrToCopy;
  _tcscpy(m_sSrcJpg, sSrcJpgName);
  _tcscpy(m_sTgtJpg, sTgtJpgName);
  m_hInst = hInst;
  m_bAbort = FALSE;
  m_nCopied = 0;
  m_bStartedCopy = FALSE;
}

CFileCopyDlg::~CFileCopyDlg()
{
}



BEGIN_MESSAGE_MAP(CFileCopyDlg, CDialog)
  ON_WM_SHOWWINDOW()
  ON_MESSAGE(WMU_POSTINIT, OnWmuPostInit)
//  ON_BN_CLICKED(IDCANCEL, OnBnCancel)
END_MESSAGE_MAP()


BOOL CFileCopyDlg::OnInitDialog()
{
  CZDialog::OnInitDialog();
  ::SendMessage(m_hWnd, WM_SETICON, TRUE,
							(LPARAM) LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_MAIN)));

  csBS.Format(_T("Copying %d files to player ..."), m_nCountToCopy);
  SetDlgItemText(IDCF_TXT_COPY, csBS);

  m_hProgress = GetDlgItem(IDCF_PROGRESS)->m_hWnd;
  ::SendMessage(m_hProgress, PBM_SETPOS, 0, 0); // in default range 0 to 100

  return TRUE;
} // BOOL CFileCopyDlg::OnInitDialog()


LRESULT CFileCopyDlg::OnWmuPostInit(WPARAM, LPARAM)
{
  if (m_bStartedCopy) return 1;
  m_bStartedCopy = TRUE;

  if (CopyFiles()) OnOK();
  else CZDialog::OnCancel(); // Not own OnCancel. Msg already unless clicked cancel

  return 1;
}

void CFileCopyDlg::OnShowWindow(BOOL bShow, UINT nStatus)
{
  CDialog::OnShowWindow(bShow, nStatus);

  if (m_bStartedCopy) return;
  PostMessage(WMU_POSTINIT); // Run CopyFiles after dialog visible
}

BOOL CFileCopyDlg::CopyFiles()
{
  INT nIxJpf;
  HANDLE hFile;
  WIN32_FIND_DATA found;
  LPCTSTR sErrCountFmt = _T("%d image files copied before error.");

  INT nProgPos = 0;
  INT nLastProgPos = 0;

  for (INT i = 0; i < m_nCountToCopy; i++)
  {
    nIxJpf = m_nArrToCopy[i];

    if (nIxJpf < 0) // Reality check for bad m_nCountToCopy
    {
      _stprintf(sBS, sErrCountFmt, m_nCopied);
      _stprintf(sBS2, _T("Invalid index number %d for file to copy."), nIxJpf);
      return fnErr(sBS2, sBS);
    }

    if (m_pJpf->GetMatchLevel(nIxJpf) > 2) // Red or orange, overwrite existing file
    {
      // Check attributes, reset if necessary
      hFile = FindFirstFile(m_pJpf->GetJpgPath(nIxJpf, m_sTgtJpg), &found);
      if (hFile != INVALID_HANDLE_VALUE)
      {
        FindClose(hFile);
        if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          _stprintf(sBS, sErrCountFmt, m_nCopied);
          return fnErr(_T("File on player with album art name is a folder,")
            _T(" can't replace with image file:"),
                       m_pJpf->GetJpgPath(nIxJpf, m_sTgtJpg), sBS);
        }
        if ( (found.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ||
             (found.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ||
             (found.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) )
        {
          if (!SetFileAttributes(m_pJpf->GetJpgPath(nIxJpf, m_sTgtJpg),
                                 FILE_ATTRIBUTE_NORMAL))
          {
            _stprintf(sBS, sErrCountFmt, m_nCopied);
            return fnSysErr(_T("Error setting file attribute of file on player")
                            _T(" to allow overwrite:"),
                            m_pJpf->GetJpgPath(nIxJpf, m_sTgtJpg), sBS);
          }
        } // if not normal file
      } // if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    } // if (gpJpf->GetMatchLevel(nIxJpf) > 2)

    if (!CopyFile(m_pJpf->GetMatchJpgPath(nIxJpf, m_sSrcJpg),
                  m_pJpf->GetJpgPath(nIxJpf, m_sTgtJpg), FALSE))
    {
      _stprintf(sBS, sErrCountFmt, m_nCopied);
      return fnSysErr(_T("Error overwriting file on player with file from computer:"),
                      m_pJpf->GetMatchJpgPath(nIxJpf, m_sSrcJpg),
                      m_pJpf->GetJpgPath(nIxJpf, m_sTgtJpg), sBS);
    }

    m_nCopied++;

    // Update progress bar
    nProgPos = (m_nCopied * 100) / m_nCountToCopy; // with integer trunction

    if (nProgPos != nLastProgPos)
    {
      nLastProgPos = nProgPos;
      ::SendMessage(m_hProgress, PBM_SETPOS, nProgPos, 0); // in default range 0 to 100
    }
    // else fraction not enough to move progress another notch

    // Handle messages, include user clicked Cancel
    zPeekMessage();

    if (m_bAbort) return FALSE;

  } // for (INT i = 0; i < m_nCountToCopy; i++)

  return TRUE;
}

void CFileCopyDlg::OnCancel()
{
  m_bAbort = TRUE;
  //CZDialog::OnCancel(); // Let CopyFiles handle it per m_bAbort
}
