# Copyright 2020 Newcastle University.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import matplotlib.pyplot as pyplot


def plot_measurements(dw, rows, study, measurement_type_id, plot_file):
    """
    Plot the value of a measurement over time.
    :param dw: data warehouse handle
    :param rows: a list of measurements generated by the other client functions. Each measurement is in the form:
                    id,time,study,participant,measurementType,
                    typeName,measurementGroup,groupInstance,trial,valType,value
    :param study: study id
    :param measurement_type_id: the measurement type of the measurements to be plotted
    :param plot_file: the name of the file into which the plot will be written
    """
    # https://matplotlib.org/api/pyplot_api.html
    if len(rows)>0:
        trans = [list(i) for i in zip(*rows)]  # transpose the list of lists
        x = trans[1]  # the data and time
        y = trans[10]  # the measurement value

        mt_info = dw.get_measurement_type_info(study, measurement_type_id)
        units = mt_info[0][3]  # get the units name
        pyplot.title(rows[0][5])
        pyplot.xlabel("Time")  # Set the x-axis label
        pyplot.ylabel(units)  # Set the y-axis label to be the units of the measurement type
        pyplot.plot(x, y)
        pyplot.savefig(plot_file)
        pyplot.close()
    else:
        print("No values to plot\n")
