#!/usr/bin/env node

const sqlite3 = require("sqlite3").verbose(),
    db = new sqlite3.Database("/tmp/iptv.sqlite"),
    languages = require("../config/languages.json"),
    countries = require("../config/countries.json"),
    categories = require("../config/categories.json");

let languageMatch = "",
    countryMatch = "",
    categoryMatch = "";

languages.forEach((language, index) => {
    languageMatch += `languages='${language}'`;

    if (index < languages.length - 1) {
        languageMatch += " OR ";
    }
});

countries.forEach((country, index) => {
    countryMatch += `country='${country}'`;

    if (index < countries.length - 1) {
        countryMatch += " OR ";
    }
});

categories.forEach((category, index) => {
    categoryMatch += `categories LIKE '%${category}%'`;

    if (index < categories.length - 1) {
        categoryMatch += " OR ";
    }
});

db.serialize(() => {
    db.each(`SELECT * FROM iptv_processed WHERE is_nsfw='FALSE' AND (${languageMatch}) AND link NOT LIKE '' AND (${countryMatch}) AND (${categoryMatch})`, (err, row) => {
        console.log(`#EXTINF:-1 tvg-id="${row.id}" tvg-logo="${row.logo}" group-title="${row.name}"`);
        console.log(row.link);
    });
});