#!/usr/bin/env python
#
# This file is part of aDBa.
#
# aDBa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# aDBa 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 aDBa.  If not, see <http://www.gnu.org/licenses/>.
from .aniDBmaper import AniDBMaper
class ResponseResolver:
    def __init__(self, data):
        restag, rescode, resstr, datalines = self.parse(data)
        self.restag = restag
        self.rescode = rescode
        self.resstr = resstr
        self.datalines = datalines
    def parse(self, data):
        resline = data.split('\n', 1)[0]
        lines = data.split('\n')[1:-1]
        rescode, resstr = resline.split(' ', 1)
        if rescode[0] == 'T':
            restag = rescode
            rescode, resstr = resstr.split(' ', 1)
        else:
            restag = None
        datalines = []
        for line in lines:
            datalines.append(line.split('|'))
        return restag, rescode, resstr, datalines
    def resolve(self, cmd):
        return responses[self.rescode](cmd, self.restag, self.rescode, self.resstr, self.datalines)
class Response:
    def __init__(self, cmd, restag, rescode, resstr, rawlines):
        self.req = cmd
        self.restag = restag
        self.rescode = rescode
        self.resstr = resstr
        self.rawlines = rawlines
        self.maper = AniDBMaper()
    def __repr__(self):
        tmp = "%s(%s,%s,%s) %s\n" % (
        self.__class__.__name__, repr(self.restag), repr(self.rescode), repr(self.resstr),
        repr(self.attrs))
        m = 0
        for line in self.datalines:
            for k, v in line.items():
                if len(k) > m:
                    m = len(k)
        for line in self.datalines:
            tmp += "  Line:\n"
            for k, v in line.items():
                tmp += "    %s:%s %s\n" % (k, (m - len(k)) * ' ', v)
        return tmp
    def parse(self):
        tmp = self.resstr.split(' ', len(self.codehead))
        self.attrs = dict(list(zip(self.codehead, tmp[:-1])))
        self.resstr = tmp[-1]
        self.datalines = []
        for rawline in self.rawlines:
            normal = dict(list(zip(self.codetail, rawline)))
            rawline = rawline[len(self.codetail):]
            rep = []
            if len(self.coderep):
                while rawline:
                    tmp = dict(list(zip(self.coderep, rawline)))
                    rawline = rawline[len(self.coderep):]
                    rep.append(tmp)
            # normal['rep']=rep
            self.datalines.append(normal)
    def handle(self):
        if self.req:
            self.req.handle(self)
class LoginAcceptedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		sesskey	- session key
		address	- your address (ip:port) as seen by the server
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'LOGIN_ACCEPTED'
        self.codetail = ()
        self.coderep = ()
        nat = cmd.parameters['nat']
        nat = int(nat == None and nat or '0')
        if nat:
            self.codehead = ('sesskey', 'address')
        else:
            self.codehead = ('sesskey',)
class LoginAcceptedNewVerResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		sesskey	- session key
		address	- your address (ip:port) as seen by the server
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'LOGIN_ACCEPTED_NEW_VER'
        self.codetail = ()
        self.coderep = ()
        nat = cmd.parameters['nat']
        nat = int(nat == None and nat or '0')
        if nat:
            self.codehead = ('sesskey', 'address')
        else:
            self.codehead = ('sesskey',)
class LoggedOutResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'LOGGED_OUT'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class ResourceResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'RESOURCE'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class StatsResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'STATS'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class TopResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'TOP'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class UptimeResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		uptime	- udpserver uptime in milliseconds
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'UPTIME'
        self.codehead = ()
        self.codetail = ('uptime',)
        self.coderep = ()
class EncryptionEnabledResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		salt	- salt
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'ENCRYPTION_ENABLED'
        self.codehead = ('salt',)
        self.codetail = ()
        self.coderep = ()
class MylistEntryAddedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		entrycnt - number of entries added
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'MYLIST_ENTRY_ADDED'
        self.codehead = ()
        self.codetail = ('entrycnt',)
        self.coderep = ()
class MylistEntryDeletedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		entrycnt - number of entries
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'MYLIST_ENTRY_DELETED'
        self.codehead = ()
        self.codetail = ('entrycnt',)
        self.coderep = ()
class AddedFileResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'ADDED_FILE'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class AddedStreamResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'ADDED_STREAM'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class EncodingChangedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'ENCODING_CHANGED'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class FileResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		eid		episode id
		gid		group id
		lid		mylist id
		state		state
		size		size
		ed2k		ed2k
		md5		md5
		sha1		sha1
		crc32		crc32
		dublang		dub language
		sublang		sub language
		quality		quality
		source		source
		audiocodec	audio codec
		audiobitrate	audio bitrate
		videocodec	video codec
		videobitrate	video bitrate
		resolution	video resolution
		filetype	file type (extension)
		length		length in seconds
		description	description
		filename	anidb file name
		gname		group name
		gshortname	group short name
		epno		number of episode
		epname		ep english name
		epromaji	ep romaji name
		epkanji		ep kanji name
		totaleps	anime total episodes
		lastep		last episode nr (highest, not special)
		year		year
		type		type
		romaji		romaji name
		kanji		kanji name
		name		english name
		othername	other name
		shortnames	short name list
		synonyms	synonym list
		categories	category list
		relatedaids	related aid list
		producernames	producer name list
		producerids	producer id list
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'FILE'
        self.codehead = ()
        self.coderep = ()
        fmask = cmd.parameters['fmask']
        amask = cmd.parameters['amask']
        codeListF = self.maper.getFileCodesF(fmask)
        codeListA = self.maper.getFileCodesA(amask)
        # print "File - codelistF: "+str(codeListF)
        # print "File - codelistA: "+str(codeListA)
        self.codetail = tuple(['fid'] + codeListF + codeListA)
class MylistResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		lid	 - mylist id
		fid	 - file id
		eid	 - episode id
		aid	 - anime id
		gid	 - group id
		date	 - date when you added this to mylist
		state	 - the location of the file
		viewdate - date when you marked this watched
		storage	 - for example the title of the cd you have this on
		source	 - where you got the file (bittorrent,dc++,ed2k,...)
		other	 - other data regarding this file
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'MYLIST'
        self.codehead = ()
        self.codetail = (
        'lid', 'fid', 'eid', 'aid', 'gid', 'date', 'state', 'viewdate', 'storage', 'source',
        'other')
        self.coderep = ()
class MylistStatsResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		animes		- animes
		eps		- eps
		files		- files
		filesizes	- size of files
		animesadded	- added animes
		epsadded	- added eps
		filesadded	- added files
		groupsadded	- added groups
		leechperc	- leech %
		lameperc	- lame %
		viewedofdb	- viewed % of db
		mylistofdb	- mylist % of db
		viewedofmylist	- viewed % of mylist
		viewedeps	- number of viewed eps
		votes		- votes
		reviews		- reviews
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'MYLIST_STATS'
        self.codehead = ()
        self.codetail = (
        'animes', 'eps', 'files', 'filesizes', 'animesadded', 'epsadded', 'filesadded',
        'groupsadded', 'leechperc', 'lameperc', 'viewedofdb', 'mylistofdb', 'viewedofmylist',
        'viewedeps', 'votes', 'reviews')
        self.coderep = ()
class AnimeResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'ANIME'
        self.codehead = ()
        self.coderep = ()
        # TODO: impl random anime
        amask = cmd.parameters['amask']
        codeList = self.maper.getAnimeCodesA(amask)
        self.codetail = tuple(codeList)
class AnimeBestMatchResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'ANIME_BEST_MATCH'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class RandomanimeResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'RANDOMANIME'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class EpisodeResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		eid	- episode id
		aid	- anime id
		length	- length
		rating	- rating
		votes	- votes
		epno	- number of episode
		name	- english name of episode
		romaji	- romaji name of episode
		kanji	- kanji name of episode
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'EPISODE'
        self.codehead = ()
        self.codetail = (
        'eid', 'aid', 'length', 'rating', 'votes', 'epno', 'name', 'romaji', 'kanji')
        self.coderep = ()
class ProducerResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		pid	  - producer id
		name	  - name of producer
		shortname - short name
		othername - other name
		type	  - type
		pic	  - picture name
		url	  - home page url
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'PRODUCER'
        self.codehead = ()
        self.codetail = ('pid', 'name', 'shortname', 'othername', 'type', 'pic', 'url')
        self.coderep = ()
class GroupResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		gid	   - group id
		rating	   - rating
		votes	   - votes
		animes	   - anime count
		files	   - file count
		name	   - name
		shortname  - short
		ircchannel - irc channel
		ircserver  - irc server
		url	   - url
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'GROUP'
        self.codehead = ()
        self.codetail = (
        'gid', 'rating', 'votes', 'animes', 'files', 'name', 'shortname', 'ircchannel', 'ircserver',
        'url')
        self.coderep = ()
class GroupstatusResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		gid	   - group id
		rating	   - rating
		votes	   - votes
		animes	   - anime count
		files	   - file count
		name	   - name
		shortname  - short
		ircchannel - irc channel
		ircserver  - irc server
		url	   - url
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'GROUPSTATUS'
        self.codehead = ()
        self.codetail = (
        'gid', 'name', 'state', ' last_episode_number', 'rating', 'votes', 'episode_range')
        self.coderep = ()
class BuddyListResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		start	- mylist entry number of first buddy on this packet
		end	- mylist entry number of last buddy on this packet
		total	- total number of buddies on mylist
		data:
		uid	- uid
		name	- username
		state	- state
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'BUDDY_LIST'
        self.codehead = ('start', 'end', 'total')
        self.codetail = ('uid', 'username', 'state')
        self.coderep = ()
class BuddyStateResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		start	- mylist entry number of first buddy on this packet
		end	- mylist entry number of last buddy on this packet
		total	- total number of buddies on mylist
		data:
		uid	- uid
		state	- online state
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'BUDDY_STATE'
        self.codehead = ('start', 'end', 'total')
        self.codetail = ('uid', 'state')
        self.coderep = ()
class BuddyAddedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'BUDDY_ADDED'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class BuddyDeletedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'BUDDY_DELETED'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class BuddyAcceptedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'BUDDY_ACCEPTED'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class BuddyDeniedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'BUDDY_DENIED'
        self.codehead = ()
        self.codetail = ()
        self.coderep = ()
class VotedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		name	- aname/ename/gname
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'VOTED'
        self.codehead = ()
        self.codetail = ('name',)
        self.coderep = ()
class VoteFoundResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		name	- aname/ename/gname
		value	- vote value
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'VOTE_FOUND'
        self.codehead = ()
        self.codetail = ('name', 'value')
        self.coderep = ()
class VoteUpdatedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:
		name	- aname/ename/gname
		value	- vote value
		"""
        Response.__init__(self, cmd, restag, rescode, resstr, datalines)
        self.codestr = 'VOTE_UPDATED'
        self.codehead = ()
        self.codetail = ('name', 'value')
        self.coderep = ()
class VoteRevokedResponse(Response):
    def __init__(self, cmd, restag, rescode, resstr, datalines):
        """
		attributes:
		data:


Answer: 		name	- aname/ename/gname