/*

  xmunipack - FITS extension side-list

  Copyright © 2019 F.Hroch (hroch@physics.muni.cz)

  This file is part of Munipack.

  Munipack 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 3 of the License, or
  (at your option) any later version.

  Munipack 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 Munipack.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "xmunipack.h"
#include <wx/treectrl.h>
#include <wx/wx.h>

#define LABEL "Extension"

MuniExtensionList::MuniExtensionList(wxWindow *w):
  wxListView(w,wxID_ANY,wxDefaultPosition,wxDefaultSize,
  	     wxLC_REPORT|wxLC_SINGLE_SEL)
{
  Bind(wxEVT_LIST_ITEM_SELECTED,&MuniExtensionList::OnExtChanged,this);
}

void MuniExtensionList::Set(const FitsMeta& meta)
{
  ClearAll();

  wxSize labelsize = GetTextExtent(LABEL);
  int size = int(1.618*labelsize.GetHeight() + 3);

  // icons
  wxImageList *icons = new wxImageList(size, size, true);
  for(size_t i = 0; i < meta.HduCount(); i++ ) {
    icons->Add(DrawIcon(size,meta.Hdu(i).Type()));
  }
  AssignImageList(icons,wxIMAGE_LIST_SMALL);

  // labels
  AppendColumn(LABEL);
  size_t len = 1.618*wxString(LABEL).Len();
  for(size_t i = 0; i < meta.HduCount(); i++) {
    wxString label = meta.Hdu(i).GetControlLabel().Capitalize();
    if( label.Len() > len)
      label = label.Mid(0,len) + "...";
    InsertItem(i,label,i);
  }

  SetColumnWidth(0,wxLIST_AUTOSIZE);
}

void MuniExtensionList::ChangeSelection(int n)
{
  Select(n);
}

void MuniExtensionList::OnExtChanged(wxListEvent& event)
{
  event.Skip();
}

wxBitmap MuniExtensionList::DrawIcon(int size, int hdutype)
{
  wxBitmap bmp(size,size);
  wxMemoryDC mdc(bmp);

  mdc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX));
  mdc.Clear();
  wxBrush brush;
  if( hdutype == HDU_IMAGE )
    brush = *wxGREY_BRUSH;
  else if( hdutype == HDU_TABLE )
    brush = wxBrush(*wxLIGHT_GREY,wxBRUSHSTYLE_CROSS_HATCH);
  else if( hdutype == HDU_HEAD )
    brush = wxBrush(*wxLIGHT_GREY,wxBRUSHSTYLE_HORIZONTAL_HATCH);
  mdc.SetBrush(brush);
  mdc.SetPen(*wxBLACK_PEN);

  int d = 3;
  mdc.DrawRoundedRectangle(wxRect(d,d,size-2*d,size-2*d),3);

  if( hdutype == HDU_IMAGE ) {
    mdc.SetPen(*wxWHITE_PEN);
    mdc.SetBrush(*wxWHITE_BRUSH);
    mdc.DrawCircle(size/3,size/2,2);
    mdc.DrawCircle(size/2,size/3,3);
    mdc.DrawCircle((2*size)/3,(2*size)/3,2);
  }

  return bmp;
}
