import traceback
import dataset
import codecs
import sys
import pickle
import os
import searchconsole


db = dataset.connect('mysql://choozmo:pAssw0rd@127.0.0.1:3306/hhh?charset=utf8mb4')
#db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')

db.begin()
#db = dataset.connect('sqlite:///:memory:')
table=db['gsc_page_query_year']
#pname='korea'
rid=0

def checkig():
    global instl
    global table
    global pname
    global rid
    lst=[]
    cntdict={}
    codelist={}
    idx=0
    flag_break=False

    fname=os.path.abspath(__file__)
    elmts=fname.split(os.path.sep)
    path2=os.path.sep.join(elmts[0:-1])
    keysdir=path2+os.path.sep+'../keys'+os.path.sep

#    account = searchconsole.authenticate(client_config='c:/keys/client_secret.json',credentials='c:/keys/credentials.json')
    account = searchconsole.authenticate(client_config=keysdir+'client_secret.json',credentials=keysdir+'credentials.json')

#    webproperty = account['https://ipromise.com.tw/']
#    webproperty = account['https://'+pname+'.face8ook.org/']
#    webproperty = account['https://www.damanwoo.com/']
    webproperty = account['https://hhh.com.tw/']

#    report=webproperty.query.range('2021-03-01', '2021-06-17').dimension('page','query').get()
#    report=webproperty.query.range('2021-06-01', '2021-06-17').dimension('page','query').get()
#    report=webproperty.query.range('2020-06-01', '2021-06-22').dimension('page','query').filter('page', '/designers/cases/(491|31|293|278|31|24|594|356|307|491|33|385)', 'equals').get()
#    report=webproperty.query.range('2020-03-01', '2021-06-22').dimension('page','query').filter('page', '/designers/cases/'+pgnum, 'contains').get()
#    report=webproperty.query.range('2020-03-01', '2021-06-22').dimension('page','query').filter('page', '/designers/cases/'+pgnum, 'contains').get()
    report=webproperty.query.range('2020-06-30', '2021-06-29').dimension('page','query').get()

    result=[]
    for r in report.rows:
        entry={'page':r[0],'query':r[1]}
        result.append(entry)

    for r in result:
        table.insert(r)
    db.commit()


r=checkig()

