const {SearchByTag, Search, Manga, Chapter, Modules, cookieParser} = require('./lib');
const fs = require('fs');
const path = require('path');

const mongoose = require('mongoose')
const FavoriteModel = require('./models/favorite.js');
const ChapterModel = require('./models/readChapter.js');
const mongoURI = 'mongodb://mongoadmin:something@192.168.71.137:27017';

mongoose.connect(mongoURI);
mongoose.connection.on('connected', ()=>{console.log('MongoDB - Connected')})
        .on('disconnected', ()=>{console.log('MongoDB - Disconnect')})
        .on('error', (error)=>console.log('Mongoose Error:', error));


        
(async ()=>
{

    async function getChaptersToContinue() 
    {
        const favs = await FavoriteModel.find();
        const chaps = await ChapterModel.find();
        const favMap = new Map(favs.map(fav => [`${fav.title}_${fav.scanlator}`, {latestComplete: null, incomplete: []}]));
        const favoritesNotYetStarted = [];
        // Filter chapters directly into their respective categories
        chaps.forEach(chap => 
            {
                const key = `${chap.title}_${chap.scanlator}`;
                if (favMap.has(key)) 
                {
                    const group = favMap.get(key);
                    if (chap.completely) {
                        if (!group.latestComplete || chap.chapterNum > group.latestComplete.chapterNum) group.latestComplete = chap;
                    }
                    else 
                    {
                        group.incomplete.push(chap);
                    }
                }
            });
        favs.forEach((element) => 
        {
            const {title, scanlator} = element;
            if (!chaps.some(chap => chap.title == title && chap.scanlator == scanlator)) {
                favoritesNotYetStarted.push(element);
            }
        });
   
        // Compile the results
        let results = Array.from(favMap.values()).flatMap(group => 
            group.latestComplete ? [group.latestComplete, ...group.incomplete] : group.incomplete
        );
        
        results = await Promise.all(results.map(async (chap) => 
        {
            if (!chap.completely) return chap;
            let next = await getNextChapter(chap);
            return next ? next : null;
        }));
        
        results = results.filter(chap => chap !== null);
        // Filter to find unique chapters that are not completed
        const uniqueContinuationChapters = chaps.filter(chap => 
            {
                return !chap.completely && !results.some(f => f.scanlator === chap.scanlator && f.title === chap.title)
            });

        const chaptersToStart = [];
        for(var i = 0; i< favoritesNotYetStarted.length; i++)
        {
            const {title, link, scanlator} =  favoritesNotYetStarted[i];
            const {List, img} = await new Manga(scanlator, link, title).get();
            let aux = {byPass:true, chapterNum:0};
            const chap = await new Chapter(scanlator, List[0].link, title, List[0].num).get();
            const imgReadOutOfTotal = 0+'/'+(chap.List.length-1)
            aux = {...aux, ...chap, mangaCoverImg:img, imgReadOutOfTotal,lastImageRead:chap.List[0]}
            chaptersToStart.push(aux);    
        }
    
        return [...results, ...uniqueContinuationChapters, ...chaptersToStart];
    }
    async function getNextChapter (chapter)
    {
        const {scanlator, link, title, chapterNum, _id } = chapter;
        const manga = await new Manga(scanlator, link, title).get();
        if((chapterNum+1)>manga.latestChap) return false;
        const chapLink = manga.List.filter(item=>item.num == (chapterNum+1))[0].link
        const nextChapter = await new Chapter(scanlator, chapLink, title, (chapterNum+1)).get();
        let index = nextChapter.List.indexOf(chapter.lastImageRead)
        const imgReadOutOfTotal = (index !=-1 ? index:0)+'/'+(nextChapter.List.length-1)
        return {
            ...nextChapter,
            _id,
            mangaCoverImg:manga.img,
            chapterNum:nextChapter.chNum,
            lastImageRead:nextChapter.List[0], 
            completely:false, 
            imgReadOutOfTotal, 
            byPass:true
        };
    }

    const chaptersToContinue = await getChaptersToContinue();
    chaptersToContinue.sort((a, b) => {
        if (a.chapterNum === 0)  return 1;
        if (b.chapterNum === 0)  return -1;
        return a.chapterNum - b.chapterNum;
    });
    for(let i = 0; i<chaptersToContinue.length; i++)
    {
        if(chaptersToContinue[i].byPass) continue
        if(!chaptersToContinue[i].mangaLink)
        {
            const {scanlator, link, title, chapterNum} = chaptersToContinue[i];
            const {List, img} = await new Manga(scanlator, link, title).get();
            if(!List.some(item=>item.num == chapterNum)) return;
            let chapter = await new Chapter(scanlator,List[chapterNum-1].link, title,chapterNum).get();           
            chaptersToContinue[i].link = chapter.link;
            let index = chapter.List.indexOf(chaptersToContinue[i].lastImageRead)
            const imgReadOutOfTotal = (index !=-1 ? index:0)+'/'+(chapter.List.length-1)
            let aux = {...chaptersToContinue[i]._doc, mangaCoverImg:img, imgReadOutOfTotal}
            chaptersToContinue[i] = aux;
        }
    }
    // console.log(chaptersToContinue)    
    const c = chaptersToContinue.filter(item=>item.title=='Kagurabachi').sort((a,b)=>a.chapterNum-b.chapterNum)
    console.log(c)
    
    // const chapter = await ChapterModel.findOneAndDelete({_id:'66251e66ab92b12ec150dad9'});
})();