"""
 Copyright (C) 2010-2013, Ryan Fan

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Library General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
import datetime as pdatetime
from datetime import datetime
import re
import pytz

def convert_naivetime_to(src_time, src_timezone, target_timezone):
    if not isinstance(src_time, datetime):
        raise

    try:
        aware_src_time = src_time.replace(tzinfo=pytz.timezone(src_timezone))
        target_time = convert_awaretime_to(aware_src_time, target_timezone)
    except:
        raise

    return target_time

def convert_awaretime_to(src_time, target_timezone):
    if not isinstance(src_time, datetime):
        raise

    try:
        target_tzinfo = pytz.timezone(target_timezone)
        target_time = target_tzinfo.normalize(src_time.astimezone(target_tzinfo))
    except:
        raise

    return target_time

def getSysTimezone():
    # try to detect system's timezone setting
    with open("/etc/sysconfig/clock") as f:
        clockSetting = f.read()

    p = re.compile(r'ZONE=\"(.*?)\"')
    founds = p.findall(clockSetting)
    if not founds:
        print "Cannot detect current system's local timezone by checking /etc/sysconfig/clock"
        raise

    sysTimezone = founds[0]

    return sysTimezone

def getLocalWorkTime(workTimezone, workStartTime="08:30:00", workEndTime="17:30:00", daysDelta=0):
    """
    Get local working time based on current time
    daysDelta > 0: Get how many days before working time(local)
    e.g:
    yesterday:                daysDelta = 1
    the day before yesterday: daysDelta = 2
    """
    # system current time
    sysNow = datetime.now()
    sysTimezone = getSysTimezone()

    # convert system current time to target local timezone
    localNow = convert_naivetime_to(sysNow, sysTimezone, workTimezone)
    localToday = "%s-%s-%s" % (localNow.year, localNow.month, localNow.day)

    # get the local day matches daysDelta setting
    localWhichDay = datetime.strptime(localToday, '%Y-%m-%d') - pdatetime.timedelta(days=daysDelta)

    # build workTime object
    workTime = {}

    workTime['day'] = "%s-%s-%s" % (localWhichDay.year, localWhichDay.month, localWhichDay.day)

    localWhichDayStartTime = "%s %s" % (workTime['day'], workStartTime)

    # for future reference, it need convert naive datetime to aware datetime
    naiveStartTime = datetime.strptime(localWhichDayStartTime, '%Y-%m-%d %H:%M:%S')
    workTime['start'] = naiveStartTime.replace(tzinfo=pytz.timezone(workTimezone))

    localWhichDayEndTime = "%s %s" % (workTime['day'], workEndTime)
    # for future reference, it need convert naive datetime to aware datetime
    naiveEndTime = datetime.strptime(localWhichDayEndTime, '%Y-%m-%d %H:%M:%S')
    workTime['end'] = naiveEndTime.replace(tzinfo=pytz.timezone(workTimezone))

    return workTime

def humanizeTime(timedelta):
    strMins = str(timedelta.seconds/60) + " mins(s)"

    strDays = ''
    if timedelta.days > 0:
        strDays = str(timedelta.days) + " day(s) "

    return strDays + strMins
