from __future__ import print_function

import json
import os
import subprocess

from helpers.mgnt_facility_agent import FacilityAgent


class AutoCheckoutData:
    def __init__(self, facility, json_dir, magnet=None):
        self.agent = FacilityAgent(facility)
        if json_dir:
            self.data_dir = json_dir
            self.local_save = True
        else:
            self.data_dir = '$MGNT_REPORT/data'
            self.local_save = False

        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)
        if self.local_save:
            if os.path.isfile(json_path):
                with open(json_path) as f:
                    self.data = json.load(f)

            else:
                print("NOTICE: {} doesn't exist yet".format(json_file))

        else:
            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)
        if self.local_save:
            with open(json_path, 'w') as f:
                json.dump(self.data, f)

        else:
            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)
        if not test_data:
            return None

        return test_data[-1]

    def get_element(self):
        return self.data['element']

    def get_device(self):
        return self.data['device']
