#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QFileDialog
from ._Display import _Display
from ..Data.Mask import Mask
from ikit import read, write
from ..Data.VizItem import VizItem

class MaskDisplay(_Display):
    def __init__(self, data=None, label=None):
        super().__init__()
        self._mask = Mask()
        if data is not None:
            self.setTo(data, label)

    def initUI(self):
        super().initUI()

        self._saveViewAction = self._contextMenu.addAction('Save view')

    def executeAction(self, action):
        if super().executeAction(action):
            return

        if action == self._saveViewAction:
            name = QFileDialog.getSaveFileName(self, 'Save current view as image', filter="Images (*.png *.ppm *.pgm *.jpg)")
            if name[0] != '':
                print('Saving image to ', name[0])
                write(name[0], self._mask.data())
            return True

        return False

    def setTo(self, data, label=None):
        if label is None and isinstance(data, VizItem):
            label = data.label

        self._mask.setTo(data)
        self._view.setData(self._mask)

        if label is None:
            if isinstance(data, str): label = data
            else: label = ''
        self.setHeadline(label)

        if data is None:
            self.setStatusMessage('Data is None')
        else:
            self.setStatusMessage('Data size is %d x %d.' % (self._mask.data().shape[1], self._mask.data().shape[0]))
