import json
import os
import subprocess

from helpers.mgnt_facility_agent import FacilityAgent


class AutoCheckoutData:
    def __init__(self, facility, magnet=None):
        self.agent = FacilityAgent(facility)
        self.data_dir = '$MGNT_REPORT/data'
        self.data = {}
        if magnet:
            self.data['element'] = magnet['element']
            self.data['device'] = magnet['device']

    def load_json(self, json_file):
        json_path = os.path.join(self.data_dir, json_file)
        try:
            self.data = json.loads(self.agent.read_file(json_path))
        except subprocess.CalledProcessError:
            print "NOTICE: {} doesn't exist yet".format(json_file)

    def update(self, test):
        test_data = self.data.get(test.test_id, [])
        results = test.get_results()
        results['description'] = test.description
        test_data.append(results)
        self.data[test.test_id] = test_data

    def save_json(self, json_file):
        json_path = os.path.join(self.data_dir, json_file)
        self.agent.write_file(json.dumps(self.data), json_path)

    def get_latest_result(self, test_id):
        test_data = self.data.get(test_id, None)
        return test_data[-1]

    def get_element(self):
        return self.data['element']

    def get_device(self):
        return self.data['device']
