import json
from helix.functions import fequal
from helix.models.coordinate import Coordinate


class Subarray(object):
    def __init__(self, subarray_number=None, origin=None, required_seismic_anchors=None, start_row=None, size=None,
                 weight=None, row_count=None, row_counted_geometrically=None, column_count=None,
                 column_counted_geometrically=None):
        self.subarray_number = subarray_number
        self.origin = origin
        self.required_seismic_anchors = required_seismic_anchors
        self.start_row = start_row
        self.size = size
        self.weight = weight
        self.row_count = row_count
        self.row_counted_geometrically = row_counted_geometrically
        self.column_count = column_count
        self.column_counted_geometrically = column_counted_geometrically

    def filter_data(self, required_data):
        required_key_names = map(lambda x: x.subarray_key(), required_data)
        d = {key: self.__dict__.get(key) for key in required_key_names}

        subarray = Subarray()
        subarray.__dict__.update(d)
        return subarray

    def is_subset(self, other):
        if not isinstance(other, self.__class__):
            return False
        for key, value in self.__dict__.items():
            if value is None:
                continue
            if other.__dict__[key] != value:
                return False
        return True

    def almost_equal(self, other, decimal=6):
        if not isinstance(other, self.__class__):
            return False
        if not fequal(self.weight, other.weight, delta=(10 ** (-decimal))):
            print("Weights are not equal to within %d decimal places, got %f, expected %f" % (decimal, self.weight, other.weight))
            return False
        for key, value in self.__dict__.items():
            if key == 'weight':
                continue
            elif other.__dict__.get(key) != value:
                print("Expected %s to be equal, got %s, expected %s" % (key, str(value), str(other.__dict__.get(key))))
                return False
        return True

    def __eq__(self, other):
        if self is other:
            return True
        if not isinstance(other, self.__class__):
            return False
        return self.__dict__ == other.__dict__

    def __repr__(self):
        def json_forcer(x):
            if isinstance(x, Coordinate):
                return x.dictionary
            return x.__dict__

        d = {key: value for (key, value) in self.__dict__.items() if value is not None}
        return json.dumps(d, sort_keys=True, default=json_forcer)
