from __future__ import print_function, division

try:
    import cPickle as pickle
except ImportError:
    import pickle

from . import six

import numpy as np


class FitInfoFile(object):

    def __init__(self, fits, mode=None):

        if isinstance(fits, six.string_types):

            if mode not in 'wr':
                raise ValueError('mode should be r or w')

            self._handle = open(fits, mode + 'b')
            self._mode = mode

            if mode == 'r':
                self._first_meta = FitInfoMeta()
                self._first_meta.model_dir = pickle.load(self._handle)
                self._first_meta.filters = pickle.load(self._handle)
                self._first_meta.extinction_law = pickle.load(self._handle)
            else:
                self._first_meta = None

            self._fits = None

        elif isinstance(fits, FitInfo):

            self._fits = [fits]

        elif isinstance(fits, (list, tuple)):

            for info in self._fits[1:]:
                if info.meta != self._fits[0].meta:
                    raise ValueError("The meta property of all FitInfo instances should match")

            self._fits = fits

        else:

            raise TypeError('fits should be a string, FitInfo instance, or iterable of FitInfo instances')

    @property
    def meta(self):
        if self._fits is None:
            if self._mode != 'r':
                raise ValueError("meta property is only available in read mode")
            return self._first_meta
        else:
            return self._fits[0].meta