# SPDX-License-Identifier: MIT
# Copyright (C) 2019-2020 Tobias Gruetzmacher
# Copyright (C) 2019-2020 Daniel Ring
import json
import re

from ..scraper import _ParserScraper


class Tapastic(_ParserScraper):
    baseUrl = 'https://tapas.io/'
    imageSearch = '//article[@class="ep-contents"]//img'
    episodeIdSearch = re.compile(r'episodeId : (\d+),')
    episodeListSearch = re.compile(r'episodeList : (.*),')
    multipleImagesPerStrip = True

    def __init__(self, name, url):
        super(Tapastic, self).__init__('Tapastic/' + name)
        self.url = self.baseUrl + 'series/' + url
        self.stripUrl = self.baseUrl + 'episode/%s'

    def starter(self):
        # Retrieve series data object
        seriesPage = self.getPage(self.url)
        dataScript = seriesPage.xpath('//script[contains(text(), "var _data")]')[0].text
        # Extract episode list
        currentEpisode = self.episodeIdSearch.findall(dataScript)[0]
        self.episodeList = json.loads(self.episodeListSearch.findall(dataScript)[0])
        return self.stripUrl % currentEpisode

    def fetchUrls(self, url, data, urlSearch):
        # Save link order for position-based filenames
        self.imageUrls = super().fetchUrls(url, data, urlSearch)
        # Update firstStripUrl with the correct episode title
        if int(url.rsplit('/', 1)[-1]) == self.episodeList[0]['id']:
            self.firstStripUrl = url
        return self.imageUrls

    def getPrevUrl(self, url, data):
        episodeId = int(url.rsplit('/', 1)[-1])
        index = [i for i, ep in enumerate(self.episodeList) if ep['id'] == episodeId][0]
        if index == 0:
            return None
        return self.stripUrl % str(self.episodeList[index - 1]['id'])

    def namer(self, imageUrl, pageUrl):
        # Construct filename from episode number and image position on page
        episodeNum = pageUrl.rsplit('/', 1)[-1]
        imageNum = self.imageUrls.index(imageUrl)
        imageExt = pageUrl.rsplit('.', 1)[-1]
        if len(self.imageUrls) > 1:
            filename = "%s-%d.%s" % (episodeNum, imageNum, imageExt)
        else:
            filename = "%s.%s" % (episodeNum, imageExt)
        return filename

    @classmethod
    def getmodules(cls):
        return (
            # Manually-added comics
            cls('NoFuture', 'NoFuture'),
            cls('OrensForge', 'OrensForge'),
            cls('RavenWolf', 'RavenWolf'),
            cls('TheCatTheVineAndTheVictory', 'The-Cat-The-Vine-and-The-Victory'),
            cls('TheGodsPack', 'The-Gods-Pack'),

            # START AUTOUPDATE
            # END AUTOUPDATE
        )

@@ -168,16 +168,54 @@
 Scraper%0A
+from ..helpers import indirectStarter%0A
 %0A%0Aclass 
@@ -307,150 +307,218 @@
 cle%5B
-@class=%22ep-contents%22%5D//img'%0A    episodeIdSearch = re.compile(r'episodeId : (%5Cd+),')%0A    episodeListSearch = re.compile(r'
+contains(@class, %22js-episode-article%22)%5D//img/@data-src'%0A    prevSearch = '//a%5Bcontains(@class, %22js-prev-ep-btn%22)%5D'%0A    latestSearch = '//ul%5Bcontains(@class, %22js-
 episode
-List : (.*),')
+-list%22)%5D//a'%0A    starter = indirectStarter
 %0A   
@@ -758,1082 +758,196 @@
 def 
-starter(self):%0A        # Retrieve series data object%0A        seriesPage = self.getPage(self.url)%0A        dataScript = seriesPage.xpath('//script%5Bcontains(text(), %22var _data%22)%5D')%5B0%5D.text%0A        # Extract episode list%0A        currentEpisode = self.episodeIdSearch.findall(dataScript)%5B0%5D%0A        self.episodeList = json.loads(self.episodeListSearch.findall(dataScript)%5B0%5D)%0A        return self.stripUrl %25 currentEpisode%0A%0A    def fetchUrls(self, url, data, urlSearch):%0A        # Save link order for position-based filenames%0A        self.imageUrls = super().fetchUrls(url, data, urlSearch)%0A        # Update firstStripUrl with the correct episode title%0A        if int(url.rsplit('/', 1)%5B-1%5D) == self.episodeList%5B0%5D%5B'id'%5D:%0A            self.firstStripUrl = url%0A        return self.imageUrls%0A%0A    def getPrevUrl(self, url, data):%0A        episodeId = int(url.rsplit('/', 1)%5B-1%5D)%0A        index = %5Bi for i, ep in enumerate(self.episodeList) if ep%5B'id'%5D == episodeId%5D%5B0%5D%0A        if index == 0:%0A            return None%0A        return self.stripUrl %25 str(self.episodeList%5Bindex - 1%5D%5B'id'%5D)
+fetchUrls(self, url, data, urlSearch):%0A        # Save link order for position-based filenames%0A        self.imageUrls = super().fetchUrls(url, data, urlSearch)%0A        return self.imageUrls
 %0A%0A  

Fix Tapastic scraper