import json
from Orm import ViewCountInfo
from playhouse.shortcuts import model_to_dict, dict_to_model


class ViewCountService:
    def createOrUpdateOne(videoId, day,count):
        query = ViewCountInfo.select().where(ViewCountInfo.videoId == videoId)
        if not query:
            countStr = "0"
            for i in range(0,30):
                if i != 29:
                    countStr = countStr + "," + "0"
            list = countStr.split(",")
            list[day-1] = count
            countStr = ""
            for i in range(0,30):
                if i != 29:
                    countStr = countStr + str(list[i]) + ","
                else:
                    countStr = countStr + str(list[i])
            ViewCountInfo.create(videoId=videoId, viewCount=countStr)
        else:
            viewCountInfo = ViewCountInfo.select().where(ViewCountInfo.videoId == videoId).get()
            list = viewCountInfo.viewCount.split(",")
            list[day-1] = count
            countStr = ""
            for i in range(0,30):
                if i != 29:
                    countStr = countStr + str(list[i]) + ","
                else:
                    countStr = countStr + str(list[i])
            ViewCountInfo.update(viewCount=countStr).where(ViewCountInfo.videoId == videoId).execute()