# bijoe - BI dashboard
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import glob
import json

from django.conf import settings
from django.utils.translation import ugettext as _

from .schemas import Warehouse


def get_warehouses(request=None):
    warehouses = []
    for pattern in settings.BIJOE_SCHEMAS:
        for path in glob.glob(pattern):
            warehouses.append(Warehouse.from_json(json.load(open(path))))
    if hasattr(request, 'tenant'):
        pattern = os.path.join(request.tenant.get_directory(), 'schemas', '*.model')
        for path in glob.glob(pattern):
            warehouses.append(Warehouse.from_json(json.load(open(path))))
    return warehouses


def human_join(l):
    if not l:
        return ''
    if len(l) == 1:
        return l[0]
    if len(l) > 2:
        l = u', '.join(l[:-1]), l[-1]
    return _(u'{0} and {1}').format(l[0], l[1])
