import unittest
import pprint
from ast import literal_eval
import urllib
import urllib.parse
import urllib.request
import pymysql
import os
# from statistic import filter

class db_connect:
    def __init__(self):
        self.db = pymysql.connect("140.114.78.48", "17sing", "musicmusic", "17sing", charset="utf8")
        self.cursor = self.db.cursor()
        self.sql_list = []

    def connect(self):
        return self.cursor

    def insert(self, table, col, value):
        #index = downloadlist.song_used_list
        #value = downloadlist.sql_song_list
        sql = "insert into %s(" % table
        sql = sql + ",".join(str(i) for i in col) + ") values"
        sql = sql + str(tuple(value))
        # print(sql)
        try:
            self.cursor.execute(sql)
            return self.db.commit()
        except Exception as e:
            print(e)
            return self.db.rollback()

    def update(self, table, col, value, condition, condval):
        print(condval)
        del(col[0])
        del(value[0])
        sql = "update %s " % table
        sql = sql + 'set '
        for i, j in zip(col, value):
            if type(j) is str:
                sql = sql + '{} = \'{}\''.format(i, j)
            else:
                sql = sql + '{} = {}'.format(i, j)
            sql = sql + ','
        sql = sql[:-1]
        sql = sql + " where " + ' and '.join('{} = {}'.format(i,str(j)) for i,j in zip(condition,condval))
        print(sql)
        try:
            self.cursor.execute(sql)
            return self.db.commit()
        except Exception as e:
            print(e)
            return self.db.rollback()


class requester:
    def __init__(self,uid,token,url='http://act.17sing.tw'):
        self.uid = uid
        self.token = token
        self.url = url
        self.pp = pprint.PrettyPrinter()

    @staticmethod
    def send_request(url):
        req = urllib.request.urlopen(url)
        json_obj = literal_eval(req.read().decode('utf-8').replace(r'\/','/'))
        try:
            ret = json_obj['response_data']
        except KeyError:
            print(json_obj)
            ret = None
        except:
            print("Unexpect error")
            ret = None


        return ret

    def print_hotlist(self):
        action = 'GetHotSearchWord'
        url = 'http://act.17sing.tw/index.php?token={}&uid={}&action={}&type=0'.format(self.uid, self.token, action)
        return self.send_request(url)

    def search_song_by_name(self,name):
        #req_list = []
        action = 'MusicSearch'
        name = urllib.request.quote(name)
        # use this for chinese cahr in url padding
        #name = urllib.parse.quote(name, safe='')
        url = 'http://act.17sing.tw/index.php?query={}&token={}&length=20&start=0&uid={}&action={}'
        #req_list.append(self.send_request(url.format(name, self.token, self.uid, action)))
        # start 是要從第幾筆開始回傳
        # length 是要一次回傳幾筆資料
        #return req_list
        songs = self.send_request(url.format(name, self.token, self.uid, action))['list']
        for song in songs:
            song['path_backup'] = song['path_backup'][0]

        return songs

    def search_song_info(self, sid):
        action = 'GetSongInfo'
        url = 'http://act.17sing.tw/index.php?token={}&sid={}&uid={}&action={}'.format(self.token, sid, self.uid, action)
        return self.send_request(url)

class SingerHandler:
    def __init__(self, singer_list, uid, token, url='http://act.17sing.tw'):
        self.singer_list = singer_list
        self.pp = pprint.PrettyPrinter()
        self.response = requester(uid, token)
        self.url = 'http://act.17sing.tw'
        self.song_list = {}

    def get(self):
        for name in self.singer_list:
            self.song_list[name] = self.response.search_song_by_name(name)
        self.pp.pprint(self.song_list)

class SongHandler:
    def __init__(self, song_list, uid ,token):
        self.song_list = song_list
        self.pp = pprint.PrettyPrinter()
        self.response = requester(uid, token)
#
# class downloader:
#     def __init__(self, like, requester, connect):
#         self.connect = connect
#         self.like = like
#         self.req = requester
#         self.song_dict = {}
#         self.user_dict = {}
#         self.song_used_list = ['id', 'name', 'listenCount', 'giftCount',
#                                'commentCount', 'praiseCount', 'sharedCount',
#                                'charm', 'flower', 'createAt', 'device', 'headset',
#                                'music', 'music_id', 'lyric', 'path', 'path_backup',
#                                'start_millisecond', 'uid']
#
#         self.user_used_list = ['uid', 'birthday', 'charmValue', 'beginTime',
#                                'endTime', 'fansNum', 'flower', 'identity',
#                                'isVip', 'musicAmount', 'sex',
#                                'singerLv', 'singerTitleLv', 'zone']
#
#         self.music_used_list = ['id', 'artist', 'artist_cn', 'path', 'path_backup',
#                                 'md5', 'music_size', 'pay_type', 'vip',
#                                 'copyright', 'tag']
#
#     def filter_like(self):
#         check_point = 1000
#         counter = 0
#
#         list = filter.get_like_greater_than(self.like)
#         for sid in list:
#             if counter % check_point == 0:
#                 print("now load %d" % counter)
#             counter +=1
#
#             json_list = self.req.search_song_info(sid)
#             if json_list:
#                 for index in self.song_used_list:
#                     self.song_dict[index] = json_list['song'][index]
#                 for index in self.user_used_list:
#                     self.user_dict[index] = json_list['user'][index]
#                 self.song_dict['path_backup'] = self.song_dict['path_backup'][0]
#                 #print(self.song_dict,self.user_dict)
#                 self.list_gen()
#                 self.connect.insert('song', self.song_used_list, self.sql_song_list)
#                 self.connect.insert('user', self.user_used_list, self.sql_user_list)
#
#     def music_trace(self, connect, req, name):
#         #pp = pprint.PrettyPrinter()
#         list = req.search_song_by_name(name)
#         #print(name)
#         #pp.pprint(list)
#         #return list
#         for sub_list in list:
#             #print(sub_list)
#             music_info = []
#             for index in self.music_used_list:
#                 try:
#                     music_info.append(sub_list[index])
#                 except TypeError:
#                     pass
#                 except IndexError:
#                     pass
#             mid = sub_list['id']
#             #print(music_info)
#             connect.insert('music', self.music_used_list, music_info)
#
#         return
#
#     def list_gen(self):
#         self.sql_song_list = [self.song_dict[item] for item in self.song_used_list]
#         self.sql_user_list = [self.user_dict[item] for item in self.user_used_list]
#         #sql_song = ','.join(self.sql_song_list)
#         #sql_user = ','.join(self.sql_user_list)
#         return
#               #def list_clean(self):


if __name__ == '__main__':
    test = db_connect()
    access = test.connect()
    uid = '4830553'
    token ='K0MMGKvcEnOh1ukKZdSrgQ7_b30zbSBUOh2-s-e4ZgCju8CQG5pDHV8v32GZmVBX4RGliU1MyAjVCjFzNpcsZK1Fg0wEdNVpCDisIIE03zI4_fxeRCUY9oA1BOpVdtpSMsoNeRA5jNIvxkQv3gD8cI1TdXlkp7tMOF6Oqd-MvWM'
    #singer_list = ['黃明志','周杰倫']
    singer_list = '清唱5分鐘'
    #singer_list = '黃明志'
    r = requester(uid,token)
    b = r.search_song_by_name(singer_list)
    a = downloader(12, r, test)
    #a.filter_like()
    #a.list_gen()
    path, _ = os.path.split(os.path.realpath(__file__))
    path = os.path.join(path, "../statistic/data/song.txt")
    f = open(path, 'r')
    count = 0
    text = f.read()
    lines = text.splitlines()

    for line in lines[:1500]:
        line = line.replace('\'','').replace('\"','')

        # print(line)
        x = a.music_trace(test, r, line)
        count = count + 1
        if count%50 is 0:
            print(count)

    #states = test.insert('song', a.song_used_list, a.sql_song_list)
    #stateu = test.insert('user', a.user_used_list, a.sql_user_list)
    #Singer = SingerHandler(singer_list, uid, token)
    #Singer.get()
