# -*- coding: utf-8 -*-
import configparser
import sqlite3

import requests

import json
from headers import headers

# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
authorization_token = config['DEFAULT']['authorization_token']
limit = config['DEFAULT']['limit']
offset = config['DEFAULT']['offset']
sort = config['DEFAULT']['sort']

headers = headers
headers['authorization'] = f'Bearer {authorization_token}'

# response = requests.get('https://trumacurl', headers=headers)

params = {
    'limit': limit,
    'offset': offset,
    # 'sort': 'oldest-first',
    'sort': sort,
}


def get_list():
    response = requests.get('https://bandu-api.songy.info/v2/communities/f0495084-4c6f-4f35-b4d5-2068641a53a1/courses',
                            params=params, headers=headers)

    # 假设response的内容就是你提供的course_list.json
    course_list_json = response.text

    # print(course_list_json)

    json_data = json.loads(course_list_json)
    course_item = json_data['data']['items']
    for item in course_item[:10]:
        print(item['id'], item['title'], item['description'])

    # 解析JSON数据
    course_list_data = json.loads(course_list_json)

    # 连接到SQLite数据库
    # 如果文件不存在，会自动在当前目录创建:
    conn = sqlite3.connect('courses.db')
    cursor = conn.cursor()

    # 创建一个表，如果它不存在:
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS courses (
        id INTEGER PRIMARY KEY,
        title TEXT,
        description TEXT
    )
    ''')

    # 插入数据
    for item in course_list_data['data']['items']:
        cursor.execute('''
        INSERT INTO courses (id, title, description)
        VALUES (?, ?, ?)
        ON CONFLICT(id) DO NOTHING
    ''', (item['id'], item['title'], item['description']))

    # 提交事务:
    conn.commit()

    # 关闭Cursor和Connection:
    cursor.close()
    conn.close()


if __name__ == '__main__':
    get_list()
