#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (C) 2012-2015 Xyne
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# (version 2) as published by the Free Software Foundation.
#
#
# 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 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import AUR.common
import gzip
import io
import logging
import os.path
import time
import urllib.request
import XCGF
import XCPF
import xdg.BaseDirectory



################################## Constants ###################################

PKGLIST_PATH = '/packages.gz'
PKGLIST_URL = AUR.common.AUR_URL + PKGLIST_PATH



################################## Functions ###################################

def iterate_packages(path):
  with gzip.open(path, 'rt') as f:
    for line in f:
      if line.startswith('#'):
        continue
      else:
        yield line.strip()



################################### Classes ####################################

class PkgList(object):
  '''
  A class to retrieve and iterate over the list of AUR packages.
  '''

  def __init__(self, path=None, ttl=AUR.common.DEFAULT_TTL, auto_refresh=False):
    if not path:
      cache_dir = xdg.BaseDirectory.save_cache_path('AUR')
      path = os.path.join(cache_dir, os.path.basename(PKGLIST_PATH))
    self.path = path
    self.ttl = ttl
    self.auto_refresh = auto_refresh



  def refresh(self, ttl=None):
    if ttl is None:
      ttl = self.ttl
    with XCGF.Lockfile(self.path + '.lck', 'PkgList') as p:
      XCGF.mirror(PKGLIST_URL, self.path, cache_time=ttl)



  def __iter__(self):
    try:
      for p in iterate_packages(self.path):
        yield p
    except FileNotFoundError:
      if self.auto_refresh:
        self.refresh()
        try:
          for p in iterate_packages(self.path):
            yield p
        except FileNotFoundError:
          pass
