from calibre.web.feeds.recipes import BasicNewsRecipe

class NGM(BasicNewsRecipe):

    title       = 'National Geographic Magazine'
    __author__  = 'Krittika Goyal'
    description = 'National Geographic Magazine'
    timefmt = ' [%d %b, %Y]'

    no_stylesheets = True
    auto_cleanup = True
    auto_cleanup_keep = '//div[@class="featurepic"]'

    def nejm_get_index(self):
        soup = self.index_to_soup('http://ngm.nationalgeographic.com/')
        a = soup.find('div', id='current_issue').find('a', href=True)
        return self.index_to_soup('http://ngm.nationalgeographic.com' + a['href'])

    # To parse artice toc
    def parse_index(self):
            soup = self.nejm_get_index()
            tocfull = soup.find('div', attrs={'class':'coltoc'})

            toc = tocfull.find('div', attrs={'class':'more_section'})

            articles = []
            feeds = []
            section_title = 'Features'
            for x in toc.findAll(True):
                if x.name == 'a':
                    # Article found
                    title = self.tag_to_string(x)
                    url = x.get('href', False)
                    if not url or not title:
                        continue
                    url = 'http://ngm.nationalgeographic.com' + url
                    self.log('\t\tFound article:', title)
                    self.log('\t\t\t', url)
                    articles.append({'title': title, 'url':url,
                        'description':'', 'date':''})
            feeds.append((section_title, articles))

            art1 = tocfull.findAll('a')[1]
            art1_title = self.tag_to_string(art1.find('div', attrs={'class': 'toched'}))
            art1_url = art1.get('href', False)
            art1_url = 'http://ngm.nationalgeographic.com' + art1_url
            art1feed = {'title': art1_title, 'url':art1_url,
                        'description':'', 'date':''}
            feeds.append(('Cover Story', [art1feed]))

            return feeds
