from __future__ import print_function
import sys
import urllib
import datetime


class getBeamCurrent(object):

    def __init__(self, startday=None, starttime=None, endday=None, endtime=None):
        if ((starttime is None) and (endtime is None)):
            print(
                "usage:python getBeamCurrent.py YYYY/mm/dd HH:MM:SS YYYY/mm/dd HH:MM:SS")
            return None
        self.s_day = startday
        self.s_time = starttime
        self.e_day = endday
        self.e_time = endtime
        self.dataList = []

        #
        # transform string to datetime.date
        # if fail return today
        #
    def _sDate2date(self, sDate):
        # sDate:'YYYY/mm/dd'
        dat = sDate.split('/')
        if 3 == len(dat):
            return datetime.date(int(dat[0]), int(dat[1]), int(dat[2]))
        else:
            return datetime.date.today()

        #
        # transform string to datetime.datetime
        # if fail return now
        #
    def _sTime2datetime(self, sTime):
        # sTime:'YYYY-mm-dd HH:MM:SS'
        dat = sTime.split(' ')
        date = dat[1].split('-')
        clock = dat[2].split(':')
        if 3 == len(date) and 3 == len(clock):
            return datetime.datetime(int(date[0]), int(date[1]), int(date[2]), int(clock[0]), int(clock[1]), int(clock[2]))
        else:
            return datetime.datetime.now()
        #
        # get one day data list from http://www-cont.j-parc.jp/MLF/cgi/
        #

    def _initializeDataList(self, getDate):
        # getDate:'YYYY/mm/dd'
        urlHead = 'http://www-cont.j-parc.jp/MLF/cgi/'
        url = urlHead + getDate + '/'
        # get file list
        print("url={}".format(url))
        src = urllib.urlopen(url).read()
        if -1 != src.find('404 Not Found'):
            return False
        line = src.split('</a>')
        urlList = []
        # get url list of YYYY-mm-ddTHH_MMBeamCurrent
        for dat in line:
            if(-1 != dat.find('BeamCurrent')):
                urlList.append(url + dat.split(' ')[2])
        src = ''
        # get data list from url list
        for dat in urlList:
            src = src + urllib.urlopen(dat).read()
        for line in src.split('\n'):
            dat = line.split('|')
            # print "len(dat)=",len(dat)
            if 5 == len(dat) and ' year ' != dat[1]:
                self.dataList.append(dat)
        print("loaded len={}".format(len(self.dataList)))
        return True

        #
        # output temperature list from data list
        #
    def _getBCList(self, sBegin, sEnd):
        i = 0
        begin = self._sTime2datetime(' ' + sBegin.replace('/', '-'))
        end = self._sTime2datetime(' ' + sEnd.replace('/', '-'))
        for i in range(0, len(self.dataList)):
            if begin <= self._sTime2datetime(self.dataList[i][0]):
                break
            nBegin = i
            for i in range((len(self.dataList) - 1), -1, -1):
                if end >= self._sTime2datetime(self.dataList[i][0]):
                    break
            nEnd = i
            nShot = 0
            tCurr = 0.
            if nBegin > nEnd:
                print("No Data")
                nShot = -1
                tCurr = -1.
            else:
                # output 'date' 'tag' 'ct9'
                # print "nBegin,nEnd+1,len(dataList)=",nBegin,(nEnd+1),len(self.dataList)
                for i in range(nBegin, (nEnd + 1)):
                    # print self.dataList[i][0]+' '+self.dataList[i][2]+' '+self.dataList[i][4]
                    nShot = nShot + 1
                    tCurr = tCurr + float(self.dataList[i][4])
        # total number of shot and total ct9
                print("Number of shot:{}, Total proton: {} [TP]".format(nShot, tCurr))
            return nShot, tCurr

    def DoIt(self):
        #
        # main routine
        #
        startday = self.s_day
        starttime = self.s_time
        endday = self.e_day
        endtime = self.e_time
        begin = self._sTime2datetime(' ' + startday.replace('/', '-') + ' ' + starttime)
        end = self._sTime2datetime(' ' + endday.replace('/', '-') + ' ' + endtime)
        if begin > end:
            print("Error:'" + startday + ' ' + starttime + "' > '" + endday + " " + endtime)
            return -1, -1.
        d = self._sDate2date(startday)
        dEnd = self._sDate2date(endday)
        td = dEnd - d
        if td.days < 8:
            td = datetime.timedelta(days=1)
        # get data list every day
            while True:
                sDate = str(d.year) + '/' + str(d.month) + '/' + str(d.day)
                if not(self._initializeDataList(sDate)):
                    print("No data in {}".format(sDate))
                    return -1, -1.
                d = d + td
                if d > dEnd:
                    break
            return self._getBCList(startday + ' ' + starttime, endday + ' ' + endtime)
        else:
            print("Overflow of days (max:7days)")
