# Copyright (C) 2017 The Meme Factory, Inc.  http://www.meme.com/
#
# 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.

# Karl O. Pinc <kop@meme.com>

'''
Print report header
'''

from __future__ import print_function

import calendar
import os
import pkg_resources
import time

from . import exceptions as ex
from . import get_rules


# Constants
BREAK_WIDTH = 50
BREAK = '=' * BREAK_WIDTH

LABEL_LEN = len('Modified by Email')
LINE_FMT = '{0:>' + repr(LABEL_LEN) + '}: {1}'


# Functions

def pretty_timestamp(timestamp):
    if time.daylight:
        adjusted = time.gmtime(timestamp - time.altzone)
    else:
        adjusted = time.localtime(timestamp)
    return time.asctime(adjusted)


def rfc3339_to_timestamp(tval):
    try:
        return calendar.timegm(time.strptime(tval, '%Y-%m-%dT%H:%M:%S.%fZ'))
    except ValueError:
        raise ex.Unrecognized3339TimeWarning(
            'The time value ({0}) cannot be reformatted'.format(tval))


def build_line(label, data):
    return LINE_FMT.format(label, data)


def optional_append(out, info, label, key):
    if key in info:
        out.append((label, info[key]))


def build_google_modtime(info):
    if 'modifiedTime' in info:
        try:
            return [('Modified', pretty_timestamp(
                rfc3339_to_timestamp(info['modifiedTime'])))]
        except ex.Unrecognized3339TimeWarning as warn:
            ex.express(warn)
            return [('Modified', info['modifiedTime'])]
    else:
        return []


def build_google_lastmod(info):
    out = []
    if 'lastModifyingUser' in info:
        lastmod = info['lastModifyingUser']
        optional_append(out, lastmod, 'Modified by User', 'displayName')
        optional_append(out, lastmod, 'Modified by Email', 'emailAddress')
    return out


def build_google_owners(info):
    out = []
    if 'owners' in info:
        # Legacy files have mutiple owners
        multi = len(info['owners']) > 1
        if multi:
            sep = '#'
            cnt = 1
        else:
            sep = ''
            cnt = ''
        for owner in info['owners']:
            optional_append(out, owner, 'Owner Name{0}{1}'.format(sep, cnt),
                            'displayName')
            optional_append(out, owner, 'Owner Email{0}{1}'.format(sep, cnt),
                            'emailAddress')
            if multi:
                cnt += 1
    return out


def build_googleinfo(info):
    out = []
    out.append(('Name', info['name']))
    optional_append(out, info, 'Version', 'version')
    out.append(('Id', info['id']))
    optional_append(out, info, 'Description', 'description')
    out.extend(build_google_modtime(info))
    out.extend(build_google_lastmod(info))
    out.extend(build_google_owners(info))
    return out


def build_fileinfo(info):
    out = []
    out.append(('Path', info['path']))
    out.append(('Modified', pretty_timestamp(info['mtime'])))
    return out


def build_metainfo(metainfo):
    (type, info) = metainfo
    out = []
    out.append(('--Sheet--  Source', type))
    if type == get_rules.FILE_SOURCE:
        out.extend(build_fileinfo(info))
    else:
        out.extend(build_googleinfo(info))
    return out


def get_version():
    return (str(pkg_resources.resource_string(__name__, 'VERSION'))
            .split('\n')[0])


def build(start_time, metainfo):
    out = []
    out.append(('Enforcer version', get_version()))
    out.append(('Start time', pretty_timestamp(start_time)))
    out.append(('Top level', os.getcwd()))
    out.extend(build_metainfo(metainfo))

    return out


def print_header(start_time, metainfo):
    out = build(start_time, metainfo)
    print(BREAK)
    for line in out:
        print(build_line(*line))
