from __future__ import print_function
import Manyo.MLF as mm
from datetime import datetime
from datetime import timedelta


class getNeutronSourceInfo(object):
    def __init__(self):
        try:
            self.ANSTI = mm.AcquireNeutronSourceTextInformation()
        except AttributeError:
            print("There is no module in your Manyo-lib.")
            return

    def getBeamCurrent(self, start_day="2009/05/30", start_time="10:00:00", end_day="2009/05/30", end_time="11:00:00", offset_sec=0.0, isCT8Neutron=False):
        ret_start = self._conv_datetime(start_day, start_time, offset_sec)
        ret_end = self._conv_datetime(end_day, end_time, offset_sec)
        if (ret_start == -1) or (ret_end == -1):
            return None

        target = "CT9"
        if isCT8Neutron:
            target = "CT8NEUTRON"

        print("     begin date and time = {} {}".format(start_day, start_time))
        print("       end date and time = {} {}".format(end_day, end_time))
        ret = self.ANSTI.PutValueInformation(target, ret_start, ret_end, -1)
        print("Beam Current (%s) = %14.4f" % (target, ret[0]))
        shots = self.ANSTI.PutShotsCounts()
        print("Shots Counts min(tag)= %d, max(tag)= %d, counts= %d" %
              (shots[0], shots[1], shots[2]))
        if (shots[0] == shots[1]):
            print("#### WARNING shots0=shots1")
            ratio = 1.0
        else:
            ratio = float(shots[2]) / float(shots[1] - shots[0])
        print("Shots Counts min(tag)= %d, max(tag)= %d, counts= %d, ratio= %g" % (shots[0], shots[1], shots[2], ratio))
        if ratio != 0:
            corrected_protons = float(ret[0]) / float(ratio)
            print("Corrected Beam Current (%s) = %14.4f" % (target, corrected_protons))
        else:
            corrected_protons = ret[0]
        return (corrected_protons, ratio, ret[0])

    def _conv_datetime(self, day_in, time_in, offset_sec=0.0):
        sd_list_s = day_in.split("/")
        sd_y = int(sd_list_s[0])
        sd_m = int(sd_list_s[1])
        sd_d = int(sd_list_s[2])
        if (sd_y < 2008) or (sd_m < 1) or (sd_m > 12) or (sd_d < 1) or (sd_d > 31):
            print("No data in such date.")
            return -1

        st_list_s = time_in.split(":")
        st_h = int(st_list_s[0])
        st_m = int(st_list_s[1])
        st_s = int(st_list_s[2])
        if (st_h < 0) or (st_h > 23) or (st_h < 0) or (st_h > 59) or (st_s < 0) or (st_s > 59):
            print("No data in such time.")
            return -1

        sd_yyyymmdd = "%04d/%02d/%02d" % (sd_y, sd_m, sd_d)
        st_hhmmss = "%02d:%02d:%02d" % (st_h, st_m, st_s)

        ret = sd_yyyymmdd + " " + st_hhmmss

        if offset_sec != 0.0:
            dateTime = datetime.strptime(ret, '%Y/%m/%d %H:%M:%S')
            # print dateTime.hour, dateTime.minute, dateTime.second
            offsetTime = timedelta(seconds=offset_sec)
            # print offsetTime.days, offsetTime.seconds
            dateTime = dateTime + offsetTime
            ret = dateTime.strftime('%Y/%m/%d %H:%M:%S')
            print("After Offset date and time = {}".format(ret))

        return ret
