#!/usr/bin/env python
# * coding: utf8 *
'''
datatable.py

A module that reads the stewardship spreadsheet and builds the sgid index page
'''

from collections import OrderedDict
from os import rename
from os.path import dirname, join
import re

import pygsheets
#: from pydash.strings import start_case


def munge_data(item, i, indices):
    names = item[indices['layer']].split('.')
    if len(names) == 1:
        category = None
        name = names[0]
    elif len(names) == 2:
        category = names[0].lower()
        name = names[1]
    elif len(names) == 3:
        category = names[0].lower()
        name = '.'.join([names[1], names[2]])

    def utf8_encode(value):
        if value is None:
            return ''

        return value

    def should_link(value):
        if value is None or len(value) == 0:
            return ''

        url = item[indices['url']]
        if url is None or len(url) == 0 or url == 'N/A':
            return utf8_encode(value)

        if url.lower().startswith('http') or url.lower().startswith('ftp'):
            return f'<a href="{url}">{utf8_encode(value)}</a>'


        anchor_tag = item[indices['anchor']]

        if anchor_tag is None or len(anchor_tag) == 0:
            return f'<a href="{{% link {url} %}}">{utf8_encode(value)}</a>'

        return f'<a href="{{% link {url} %}}#{anchor_tag}">{utf8_encode(value)}</a>'

    def endpoint_link(value):
        if value is None or len(value) == 0:
            return ''

        if ',' in value:
            value = value.split(',')

            return ''.join([f'<a href="{v}" class="pull-right">{{% include fa_icon.html api=true class="svg-inline--fa fa-w-20 fa-fw" %}}</i></a>' for v in value])

        return f'<a href="{value}" class="pull-right">{{% include fa_icon.html api=true class="svg-inline--fa fa-w-20 fa-fw" %}}</i></a>'

    def webapp_link(value):
        if value is None or len(value) == 0:
            return ''

        if ',' in value:
            value = value.split(',')

            return ''.join([f'<a href="{v.strip()}" class="pull-right">{{% include fa_icon.html globe=true class="svg-inline--fa fa-w-16 fa-fw" %}}</a>' for v in value])

        return f'<a href="{value.strip()}" class="pull-right">{{% include fa_icon.html globe=true class="svg-inline--fa fa-w-16 fa-fw" %}}</a>'

    def booleanize(value):
        if value is None or len(value) == 0:
            return False

        return True


    return OrderedDict([
        ('category', utf8_encode(category)),
        ('name', should_link(start_case(name.replace('_', ' ')))),
        ('deprecated', booleanize(item[indices['deprecated']])),
        ('agency', utf8_encode(item[indices['data_source']])),
        ('description', utf8_encode(item[indices['description']])),
        ('service', ''.join([endpoint_link(item[indices['endpoint']]), webapp_link(item[indices['web_app']])
        ]))
    ])


def get_sheet_data(gc, sheet_id, worksheet_id):
    worksheet = gc.open_by_key(sheet_id).worksheet_by_title(worksheet_id)
    data = worksheet.get_all_values(returnas='matrix')

    header = data.pop(0)
    indices = {
        'layer': header.index('SGID Data Layer'),
        'description': header.index('Description'),
        'data_source': header.index('Data Source'),
        'url': header.index('Website URL'),
        'anchor': header.index('Anchor'),
        'data_type': header.index('Data Type'),
        'endpoint': header.index('Endpoint'),
        'web_app': header.index('Webapp'),
        'deprecated': header.index('Deprecated')
    }