import json
from numpy import array


class CalculatedDataRepository(object):
    summary_values_key = 'summary_values'
    computed_csv_columns_key = 'computed_csv_columns'
    compute_bom_key = 'compute_bom'
    subarray_summary_key = 'subarray_summary'

    def __init__(self, store, calculator):
        self.store = store
        self.calculator = calculator

    def reset_data(self):
        pass

    def reset_site_data(self):
        pass

    def reset_panel_data(self):
        pass

    def reset_subarray_data(self):
        self.store.delete(self.summary_values_key)
        self.store.delete(self.subarray_summary_key)

    def reset_ebom_data(self):
        self.store.delete(self.compute_bom_key)

    def k_z(self):
        return self.calculator.k_z()

    def L_B(self):
        return self.calculator.L_B()

    def summary_table(self):
        return self.calculator.summary_table()

    def minimum_array_sizes(self):
        return self.calculator.minimum_array_sizes()

    def summary_values(self):
        key = self.summary_values_key
        if self.store.exists(key):
            summary_values_json = self.store.get(key).decode('utf-8)')
            return array(json.loads(summary_values_json))
        summary_values = self.calculator.summary_values()
        self.store.set(key, json.dumps(list(summary_values)))
        return summary_values

    def get_computed_csv_columns(self):
        return self.calculator.get_computed_csv_columns() # TODO: revisit after getting rid of DataMatrix
        # key = self.computed_csv_columns_key
        # if self.store.exists(key):
        #     computed_csv_columns_json = self.store.get(key).decode('utf-8')
        #     return jsonpickle.decode(computed_csv_columns_json)
        # computed_csv_columns = self.calculator.get_computed_csv_columns()
        # self.store.set(key, jsonpickle.encode(computed_csv_columns))
        # return computed_csv_columns

    def compute_bom(self):
        key = self.compute_bom_key
        if self.store.exists(key):
            compute_bom_json = self.store.get(key).decode('utf-8')
            return array(json.loads(compute_bom_json))
        computed_bom = self.calculator.compute_bom()
        self.store.set(key, json.dumps(computed_bom.tolist()))
        return computed_bom

    def subarray_summary(self):
        key = self.subarray_summary_key
        if self.store.exists(key):
            received_json = self.store.get(key).decode('utf-8')
            return array(json.loads(received_json))
        data = self.calculator.subarray_summary()
        self.store.set(key, json.dumps(data.tolist()))
        return data
