#
#CVIssueCount.py
#
#Author: Quinyd
#
#Description: Complete series count with the Comic Vine issue count
#
#Versions:
#               0.1 First version
#               0.2 Fixed Multiple book search
#
#
#ComicRack Declarations
#
#@Name  CVIssueCount
#@Hook  Books
#@Key   CVIssueCount
#@PCount 0

# $ cd "..\..\Program Files\ComicRack\
# $ ComicRack.exe -ssc

from __future__ import unicode_literals

import clr, re, sys, os, urlparse, time

from System.Diagnostics import Process
clr.AddReference("System.xml")
import System
from System import *
from System.IO import *
from System.Collections import *
from System.Threading import *
from System.Net import *
from System.Text import *

clr.AddReference('System')
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import *
clr.AddReference('System.Drawing')
from System.Drawing import Point, Size, ContentAlignment, Color, SystemColors, Icon
from datetime import datetime
import ssl, urllib


def CVIssueCount(books):

    API_KEY="<API_KEY>"

    # Load all books in library
    
    all_books_original = ComicRack.App.GetLibraryBooks()
    
    # Dictionaries to be used

    MaxCountList= dict()
    NumberList=dict()
    VolumeJumps=dict()

    seriesVolume=-999999

    IssueCount=0

    CheckedVolumes=list()
    IssueCountList=list()
        
    # I look for data in the books in Library

    for book in books:
        volume = book.GetCustomValue("comicvine_volume")
        if not MaxCountList.has_key(volume):
        
            # I start default values
            
            MaxCountList[volume] = -999999
            NumberList[volume] = list()
            
        try:
    
            # I look for highest number in each volume
            
            if int(float(book.Number)) > MaxCountList[volume] and int(float(book.Number)) < 1000 :
                MaxCountList[volume] = int(book.Number)
                
            # I store numbers of each volume

            NumberList[volume].append([book.Year*12+book.Month,int(float(book.Number))])
            
        except Exception,e: print str(e)
    for volume in NumberList.keys():
        seriesVolume = volume

        

        QUERY = "https://comicvine.gamespot.com/api/volume/4050-"+ volume +"/?api_key=" + API_KEY + "&format=xml&field_list=count_of_issues"

        # print QUERY

        if volume not in CheckedVolumes:
            #print "Getting info for " + volume
            data = _read_url(QUERY.encode('utf-8'))
            # time.sleep(3)
            # print Text.Json.RootElement.GetProperty("count_of_issues");

            doc = System.Xml.XmlDocument()
            doc.LoadXml(data)
            elemList = doc.GetElementsByTagName("count_of_issues")
            
            for i in elemList:
                IssueCount = int(i.InnerXml)
            print str(volume) + "'s count is " + str(IssueCount)
            CheckedVolumes.append(volume)
            IssueCountList.append(IssueCount)
        
            for book in all_books_original:
                if book.SeriesComplete:
                    volume = book.GetCustomValue("comicvine_volume")
                    if volume == seriesVolume:
                        if book.Number.isnumeric:
                            # print "Setting count to " + str(IssueCount) + " for comics with Series " + book.Series + "(" + book.GetCustomValue("comicvine_volume") + ")"
                            book.Count = IssueCount
                            book.SetCustomValue("comicvine_issue_count",str(IssueCount))

def _read_url(url):
        
    page = '' 
        
    requestUri = url

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

    Req = HttpWebRequest.Create(requestUri)  
    Req.Timeout = 60000
    Req.UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' 
    Req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip       
    
    #Req.Referer = requestUri
    Req.Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
    Req.Headers.Add('Accept-Language','en-US,en;q=0.9,it;q=0.8,fr;q=0.7,de-DE;q=0.6,de;q=0.5')
    
    Req.KeepAlive = True        
    webresponse = Req.GetResponse() 

    a = webresponse.Cookies 

    inStream = webresponse.GetResponseStream()      
    encode = Encoding.GetEncoding("utf-8")
    ReadStream = StreamReader(inStream, encode)
    page = ReadStream.ReadToEnd()

            
    try:
        inStream.Close()    
        webresponse.Close()
    except:
        pass
    
    return page